Note
This content is translated by LLM. Original text can be found here
A Golang logging package with automatic rotation, multi-level log classification, file management capabilities, and comprehensive error handling mechanisms.
Primarily designed for use inpardnchiu/go-*packages
JSON uses Go's standard log/slog package for structured logging
Text adopts tree structure to enhance readability
Supports 8 levels (DEBUG, TRACE, INFO, NOTICE, WARNING, ERROR, FATAL, CRITICAL)
Automatically rotates and creates backups when files reach size limits, intelligently cleans expired files to maintain configured backup count
go get github.com/pardnchiu/go-loggerpackage main
import (
"fmt"
"errors"
"github.com/pardnchiu/go-logger"
)
func main() {
config := &goLogger.Log{
Path: "./logs", // Log directory
Stdout: true, // Also output to terminal
MaxSize: 16 * 1024 * 1024, // 16MB file size limit
MaxBackup: 5, // Keep 5 backup files
Type: "json", // "json" for slog standard, "text" for tree format
}
// Initialize
logger, err := goLogger.New(config)
if err != nil {
panic(err)
}
defer logger.Close()
// Log messages at different levels
logger.Debug("This is debug message", "detailed debug info")
logger.Trace("Trace program execution flow")
logger.Info("General information message")
logger.Notice("Message that needs attention")
logger.Warn("Warning message")
// Error handling
err = errors.New("an error occurred")
logger.WarnError(err, "Warning message for handling error")
logger.Error(err, "Additional message for handling error")
logger.Fatal(err, "Critical error")
logger.Critical(err, "System critical error")
// Flush cache
logger.Flush()
}type Log struct {
Path string // Log file directory path (default: ./logs)
Stdout bool // Whether to output to stdout (default: false)
MaxSize int64 // Maximum log file size in bytes (default: 16MB)
MaxBackup int // Maximum number of backup files (default: 5)
Type string // Output format: "json" for slog standard, "text" for tree format (default: "text")
}When Type: "json", logs are output in log/slog structured format:
{"timestamp":"2024/01/15 14:30:25.123456","level":"INFO","message":"Application started","data":null}
{"timestamp":"2024/01/15 14:30:25.123457","level":"ERROR","message":"Database connection failed","data":["Connection timeout","Retry in 5 seconds"]}- Directly uses Go's standard
log/slogpackage - Easy integration with log aggregation tools
- Consistent JSON schema across all log levels
When Type: "text", logs are displayed in tree format:
2024/01/15 14:30:25.123457 [ERROR] Database connection failed
2024/01/15 14:30:25.123457 ├── Connection timeout
2024/01/15 14:30:25.123457 └── Retry in 5 seconds
- Clear hierarchical message structure
- Enhanced readability during debugging
Logged to debug.log
logger.Debug("Variable values", "x = 10", "y = 20")
logger.Trace("Function call", "Started processing user request")Logged to output.log
logger.Info("Application started") // No prefix
logger.Notice("Configuration file reloaded") // [NOTICE] prefix
logger.Warn("Memory usage is high") // [WARNING] prefix
logger.WarnError(err, "Non-system-affecting error") // [WARNING] prefixLogged to error.log
logger.Error(err, "Retry attempt 3") // [ERROR] prefix
logger.Fatal(err, "Unable to start service") // [FATAL] prefix
logger.Critical(err, "System crash") // [CRITICAL] prefix-
New - Create a new logger instance
logger, err := goLogger.New(config)
- Initialize log directory, ensure path exists
- Initialize three log files:
debug.log,output.log,error.log - Set up log handlers for each level
-
Close - Properly close the logger
err := logger.Close()
- Mark logger as closed
- Ensure no resource leaks
-
Flush - Force write to files
err := logger.Flush()
- Write all cached log content to disk
- Ensure logs are not lost
- Check file size before each log write
- Automatically rotate when exceeding
MaxSizelimit - Backup file naming format:
filename.YYYYMMDD_HHMMSS
- Keep the latest
MaxBackupbackup files - Automatically delete expired old backups
- Sort by modification time, keep the newest files
This project is licensed under the MIT License.
©️ 2025 邱敬幃 Pardn Chiu