### Minimal Example Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/quick-reference.md Demonstrates the basic setup for using the lumberjack logger by setting its output destination and configuration. ```APIDOC ## Minimal Example ```go import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) func main() { log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, }) // ... rest of your application logging } ``` ``` -------------------------------- ### Minimal Lumberjack Logger Setup Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/quick-reference.md Example of setting up a lumberjack logger with specific configuration for filename, maximum size, number of backups, and log age. Ensure the 'log' package is imported. ```go log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, }) ``` -------------------------------- ### Quick Start: Implement Lumberjack Logging Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/00-START-HERE.md Configure the standard Go log package to use lumberjack for automatic log file rotation. This setup is quick and requires minimal code. ```go import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 28, // days }) log.Println("Logging with automatic rotation") ``` -------------------------------- ### Basic File Logging Setup Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/00-START-HERE.md Demonstrates setting the standard library's log output to a lumberjack logger for basic file logging. Ensure the log file path is accessible. ```go log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/app.log", }) log.Println("Hello, world") ``` -------------------------------- ### Handle Error Getting Log File Info Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md If `os.Stat()` fails on the log file during initialization (e.g., due to permissions), this error occurs. This example demonstrates how to catch and handle such file access issues. ```go l := &lumberjack.Logger{Filename: "/var/log/restricted.log"} _, err := l.Write([]byte("test")) if err != nil && strings.Contains(err.Error(), "error getting log file info") { // Handle stat failure log.Fatal("Cannot access log file:", err) } ``` -------------------------------- ### Example: Graceful Log Rotation with SIGHUP Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/api-reference/logger.md This example demonstrates how to use the Rotate function in response to a SIGHUP signal. It sets up signal handling to trigger log rotation when the operating system sends a SIGHUP, ensuring graceful log management. The logger is configured with filename, max size, max backups, and max age. ```go package main import ( "log" "os" "os/signal" "syscall" "gopkg.in/natefinch/lumberjack.v2" ) func main() { l := &lumberjack.Logger{ Filename: "/var/log/myapp/server.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, } defer l.Close() log.SetOutput(l) // Set up signal handling for graceful rotation sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGHUP) go func() { for range sigChan { if err := l.Rotate(); err != nil { log.Printf("Failed to rotate log: %v", err) } } }() // Application continues... log.Println("Server running") select {} } ``` -------------------------------- ### Start Background Mill Goroutine Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/implementation-details.md Initializes and starts the asynchronous cleanup and compression goroutine using sync.Once to ensure it runs only once, even with concurrent calls. ```go l.startMill.Do(func() { l.millCh = make(chan bool, 1) go l.millRun() }) ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/quick-reference.md Example of how to configure Lumberjack using a JSON file. This configuration sets the log file path, size limits, age limits, backup counts, and compression settings. ```json { "filename": "/var/log/app.log", "maxsize": 100, "maxage": 28, "maxbackups": 3, "localtime": false, "compress": true } ``` -------------------------------- ### Basic Lumberjack Logger Setup with Go's log package Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/00-START-HERE.md Configure Go's standard log package to use Lumberjack for log rotation. Ensure the logger options are set according to your needs for file size, backups, and age. ```go package main import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) func main() { log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, MaxBackups: 3, MaxAge: 28, Compress: true, }) log.Println("Your app is now logging with automatic rotation!") } ``` -------------------------------- ### Programmatic Configuration of Lumberjack Logger in Go Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/configuration.md Configure Lumberjack logger settings directly in Go code. This example shows how to set filename, max size, max backups, max age, and compression, then directs the standard log output to this logger. ```go package main import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) func main() { logger := &lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 28, // days Compress: true, } defer logger.Close() log.SetOutput(logger) log.Println("Logging configured with rotation") } ``` -------------------------------- ### Handle Cannot Rename Log File Error Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md This example shows how to detect and manage errors that occur when the current log file cannot be renamed during the rotation process, which can happen due to filesystem limitations or file locking. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 1, } // Simulate rename failure scenario _, err := logger.Write([]byte("x")) // Fill the file if err != nil && strings.Contains(err.Error(), "can't rename log file") { log.Fatal("Cannot rotate log file:", err) } ``` -------------------------------- ### Production Logging with Rotation Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/00-START-HERE.md Configures lumberjack for production use with specified file size, backup count, age limit, and compression for rotated logs. This setup ensures efficient log management. ```go log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, // 100 MB MaxBackups: 3, // keep 3 backups MaxAge: 28, // 28 days Compress: true, // gzip old files }) ``` -------------------------------- ### Configuration from YAML Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Load logger configuration from a YAML file using an external YAML package. Ensure the logger is closed using `defer`. ```go package main import ( "io/ioutil" "log" "gopkg.in/natefinch/lumberjack.v2" "gopkg.in/yaml.v2" ) func main() { configData, _ := ioutil.ReadFile("config.yaml") var logger lumberjack.Logger yaml.Unmarshal(configData, &logger) defer logger.Close() log.SetOutput(&logger) log.Println("Configured from YAML") } ``` ```yaml filename: /var/log/myapp/app.log maxsize: 100 maxage: 28 maxbackups: 3 compress: true ``` -------------------------------- ### Configuration from JSON Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Load logger configuration by unmarshaling JSON data into the Logger struct. Remember to defer the logger's close method. ```go package main import ( "encoding/json" "io/ioutil" "log" "gopkg.in/natefinch/lumberjack.v2" ) func main() { configData, _ := ioutil.ReadFile("config.json") var logger lumberjack.Logger json.Unmarshal(configData, &logger) defer logger.Close() log.SetOutput(&logger) log.Println("Configured from JSON") } ``` ```json { "filename": "/var/log/myapp/app.log", "maxsize": 100, "maxage": 28, "maxbackups": 3, "compress": true } ``` -------------------------------- ### Initialize Logger with Configuration Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/package-overview.md Instantiate a lumberjack logger with desired configuration options. This is typically done once per application and passed to a logging package. ```go log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, MaxBackups: 3, MaxAge: 28, }) ``` -------------------------------- ### Logger Configuration and Usage Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/README.md Demonstrates how to import the lumberjack logger and configure its basic settings for file logging. ```APIDOC ## Import Path ```go import "gopkg.in/natefinch/lumberjack.v2" ``` ## Basic Usage ```go log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 28, // days Compress: true, }) ``` ``` -------------------------------- ### Signal-Based Log Rotation (SIGHUP) Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/00-START-HERE.md Sets up a goroutine to listen for SIGHUP signals and trigger manual log rotation using the logger's Rotate method. This allows for external control over log file rotation. ```go logger := &lumberjack.Logger{Filename: "/var/log/app.log"} log.SetOutput(logger) go func() { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGHUP) for range sigChan { logger.Rotate() } }() ``` -------------------------------- ### Configure Lumberjack with Combination Cleanup Policy Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Use both `MaxBackups` and `MaxAge` to enforce both a file count limit and a maximum age for log files. Files exceeding either limit will be deleted. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 30, // Keep at most 30 backups MaxAge: 90, // Also delete if older than 90 days } ``` -------------------------------- ### Initialize Lumberjack Logger with Default Settings Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/00-START-HERE.md Creates a new Lumberjack Logger instance using default configuration values. This is useful for quick testing but not recommended for production environments. ```go logger := &lumberjack.Logger{} ``` -------------------------------- ### Configure Lumberjack with No Cleanup Policy Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Set both `MaxBackups` and `MaxAge` to 0 to disable log file cleanup. All backup files will be retained indefinitely. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 0, // No count limit MaxAge: 0, // No age limit Compress: false, } ``` -------------------------------- ### Basic Lumberjack Usage Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/README.md Configure and set lumberjack as the output for the standard log package. This snippet demonstrates setting the log file path, maximum size, number of backups, age of backups, and compression. ```go log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 28, // days Compress: true, }) ``` -------------------------------- ### Handle Cannot Open New Log File Error Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md Implement this pattern to gracefully handle situations where opening or creating a new log file fails, often due to insufficient permissions, a full filesystem, or an invalid path. ```go l := &lumberjack.Logger{ Filename: "/dev/null/impossible/path.log", } _, err := l.Write([]byte("test")) if err != nil && strings.Contains(err.Error(), "can't open new logfile") { log.Fatal("Cannot open log file:", err) } ``` -------------------------------- ### Import Lumberjack Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/README.md Import the lumberjack v2 package to use its logging functionalities. ```go import "gopkg.in/natefinch/lumberjack.v2" ``` -------------------------------- ### Basic Logger Integration with Standard Log Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Use Logger directly with Go's standard log package for simple logging. All configuration is done via struct fields. ```go package main import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) func main() { log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 28, // days }) log.Println("Application started") } ``` -------------------------------- ### JSON and YAML Support Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/types.md Explains how the Logger struct fields are tagged for serialization, enabling configuration to be loaded from JSON or YAML files. ```APIDOC ### JSON and YAML Support Logger struct fields are tagged for serialization with both JSON and YAML: - Filename → `json:"filename"` / `yaml:"filename"` - MaxSize → `json:"maxsize"` / `yaml:"maxsize"` - MaxAge → `json:"maxage"` / `yaml:"maxage"` - MaxBackups → `json:"maxbackups"` / `yaml:"maxbackups"` - LocalTime → `json:"localtime"` / `yaml:"localtime"` - Compress → `json:"compress"` / `yaml:"compress"` This enables Logger configuration to be loaded from JSON or YAML configuration files. ``` -------------------------------- ### Custom Directory Structure for Logs Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Organizes log files into subdirectories based on the current date by dynamically constructing the filename path. Ensure the logger is closed properly using defer. ```go import ( "fmt" "time" "gopkg.in/natefinch/lumberjack.v2" ) func main() { // Logs organized by date todayDir := time.Now().Format("2006/01/02") logPath := fmt.Sprintf("/var/log/app/%s/app.log", todayDir) logger := &lumberjack.Logger{ Filename: logPath, MaxSize: 100, MaxBackups: 3, MaxAge: 28, } defer logger.Close() // Use logger... } ``` -------------------------------- ### Configure Lumberjack Logger with Standard Log Package Source: https://github.com/natefinch/lumberjack/blob/v2.0/README.md Use this snippet to integrate Lumberjack with Go's standard library log package. Pass a configured lumberjack.Logger instance to log.SetOutput. Ensure the log directory exists and is writable. ```go log.SetOutput(&lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 28, //days Compress: true, // disabled by default }) ``` -------------------------------- ### Handle Cannot Create Log Directory Error Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md Use this code to catch and handle errors when the log directory cannot be created due to permission issues or other filesystem restrictions. ```go l := &lumberjack.Logger{ Filename: "/root/restricted/app.log", // no write permission } _, err := l.Write([]byte("test")) if err != nil && strings.Contains(err.Error(), "can't make directories") { log.Fatal("Cannot create log directory:", err) } ``` -------------------------------- ### Simple Error Checking with Lumberjack Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md Demonstrates basic error checking after performing a manual rotation of the lumberjack logger. Ensure the logger is properly initialized before use. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, } defer logger.Close() if err := logger.Rotate(); err != nil { log.Printf("Manual rotation failed: %v", err) } ``` -------------------------------- ### Size-Based Log Rotation with Gzip Compression Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Automatically rotate logs when a specified size is reached, with old log files compressed using gzip. This pattern helps manage disk space and keeps log archives manageable. Configure MaxSize, MaxBackups, and MaxAge for desired retention. ```go package main import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) func main() { logger := &lumberjack.Logger{ Filename: "/var/log/myapp/app.log", MaxSize: 50, // Rotate when 50 MB is reached MaxBackups: 10, // Keep 10 backup files MaxAge: 365, // Keep files for 1 year Compress: true, // Compress old files with gzip } defer logger.Close() log.SetOutput(logger) // Log until rotation occurs for i := 0; i < 10000; i++ { log.Printf("Message %d: This is a test log message for rotation demo\n", i) } } ``` -------------------------------- ### Default Max Size Calculation Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/implementation-details.md Calculates the maximum log file size. If MaxSize is not specified, it defaults to 100 megabytes. ```go func (l *Logger) max() int64 { if l.MaxSize == 0 { return int64(defaultMaxSize * megabyte) // 100 MB } return int64(l.MaxSize) * int64(megabyte) } ``` -------------------------------- ### Mockable Variables for Testing Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/implementation-details.md Package-level variables can be reassigned to control behavior during tests. This allows for mocking time, simulating file errors, and controlling file sizes without actual I/O. ```go var ( currentTime = time.Now // Can mock to control time osStat = os.Stat // Can mock to simulate file errors megabyte = 1024 * 1024 // Can mock to avoid writing large files osChown = os.Chown // Can mock (Linux only) ) ``` -------------------------------- ### Define Timestamp Format for Backups Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/implementation-details.md Sets the global format for backup timestamps, ensuring they are RFC 3339-like, include milliseconds, and are alphabetically sortable. ```go backupTimeFormat = "2006-01-02T15-04-05.000" ``` -------------------------------- ### Implement io.Writer with Logger Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/api-reference/logger.md Implements the io.Writer interface for the Logger. Writes data to the log file, triggering rotation if necessary. If a write would cause the log file to exceed MaxSize, the current file is closed, renamed to include a timestamp, and a new log file is created. Returns an error if the write length exceeds MaxSize. ```go func (l *Logger) Write(p []byte) (n int, err error) ``` ```go package main import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) func main() { l := &lumberjack.Logger{ Filename: "/var/log/myapp/foo.log", MaxSize: 100, // megabytes MaxBackups: 3, MaxAge: 28, // days } defer l.Close() log.SetOutput(l) log.Println("Application started") } ``` -------------------------------- ### Configure Lumberjack to Keep Recent Files by Count Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Set `MaxBackups` to limit the number of old log files retained. When the limit is reached, the oldest backup file is deleted. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 5, // Keep only 5 most recent backups MaxAge: 0, // No age-based deletion } ``` -------------------------------- ### Logger Core Methods Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/00-START-HERE.md Outlines the primary methods of the Logger type: Write for logging with auto-rotation, Close for file handling, and Rotate for manual rotation triggers. ```go // Write() implements io.Writer — writes with auto rotation func (l *Logger) Write(p []byte) (n int, err error) ``` ```go // Close() implements io.Closer — closes the log file func (l *Logger) Close() error ``` ```go // Rotate() — manually trigger rotation (e.g., on SIGHUP) func (l *Logger) Rotate() error ``` -------------------------------- ### Configure Lumberjack to Keep Recent Files by Age Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Set `MaxAge` to a number of days to retain only log files younger than the specified age. `MaxBackups` should be 0 for age-based deletion only. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 0, // No count limit MaxAge: 7, // Keep files younger than 7 days } ``` -------------------------------- ### Logger Configuration with Local Time Timestamps Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Configures the logger to use the system's local time for timestamps in backup filenames. This setting only affects filenames, not cleanup age calculations. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, LocalTime: true, // Use local time } // Backup: app-2024-01-15T14-30-00.000.log (local time, e.g., EST) ``` -------------------------------- ### Write Method Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/quick-reference.md The Write method implements the io.Writer interface, appending data to the log file and triggering rotation if the maximum size is exceeded. ```APIDOC ## Write Method ### Signature ```go func (l *Logger) Write(p []byte) (n int, err error) ``` ### Description Writes data to the log file. Rotates the log file if the write operation would exceed the `MaxSize` configuration. ### Parameters - **p** ([]byte) - The data to write to the log. ### Returns - **n** (int) - The number of bytes written. - **err** (error) - Returns an error if the write size exceeds `MaxSize`. ``` -------------------------------- ### Logger Usage Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/types.md Outlines the common use cases for the Logger type, such as integration with Go's standard log package, use as an `io.Writer`, and scenarios requiring automatic log rotation, compression, and cleanup. ```APIDOC ### Usage Logger is used by: - Applications integrating with Go's standard `log` package via `log.SetOutput()` - Any code that requires an `io.Writer` for log output - Applications that need automatic log rotation based on file size - Systems requiring log file compression and age-based cleanup policies ``` -------------------------------- ### Logging Wrapper for Safe Log Writes Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md Provides a robust pattern for handling errors during log writes by implementing a wrapper around the lumberjack logger. This wrapper logs any write failures to a separate error log. ```go type SafeLogger struct { l *lumberjack.Logger errorLog *log.Logger } func (sl *SafeLogger) Write(p []byte) (int, error) { n, err := sl.l.Write(p) if err != nil { sl.errorLog.Printf("Failed to write log: %v", err) } return n, err } ``` -------------------------------- ### Type-Based Error Handling for Log File Permissions Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md Illustrates how to handle specific error types, such as permission errors, when writing to a lumberjack log file. This pattern helps in differentiating between various failure causes. ```go import "os" logger := &lumberjack.Logger{Filename: "/var/log/app.log"} _, err := logger.Write(data) if err != nil { if os.IsPermission(err) { log.Fatal("Permission denied on log file") } else { log.Fatal("Other error:", err) } } ``` -------------------------------- ### Error Handling for Logger Operations Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Demonstrates how to check for errors when closing or rotating the logger. Write errors are implicitly handled by the standard log package. ```go package main import ( "log" "gopkg.in/natefinch/lumberjack.v2" ) func main() { logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, } // Handle close errors if err := logger.Close(); err != nil { log.Fatalf("Failed to close logger: %v", err) } // Handle rotation errors if err := logger.Rotate(); err != nil { log.Fatalf("Failed to rotate logs: %v", err) } // Handle write errors implicitly (logged by log package) log.SetOutput(logger) log.Println("Logging with error handling") } ``` -------------------------------- ### Integrate Lumberjack with Zap Logger Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Use `zapcore.AddSync` to wrap a lumberjack logger, allowing Zap to write logs through the lumberjack rotation mechanism. Ensure necessary imports for Zap and lumberjack. ```go import ( "gopkg.in/natefinch/lumberjack.v2" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) func main() { w := zapcore.AddSync(&lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, }) core := zapcore.NewCore( zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), w, zap.InfoLevel, ) logger := zap.New(core) defer logger.Sync() logger.Info("Application started") } ``` -------------------------------- ### Handle Write Exceeding Max File Size Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md When writing data that exceeds the configured MaxSize, an error is returned. This snippet shows how to check for and handle this specific error. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 1, // 1 megabyte } // This write will fail because 2MB > 1MB data := make([]byte, 2*1024*1024) _, err := logger.Write(data) // err: "write length 2097152 exceeds maximum file size 1048576" ``` ```go if err != nil { if strings.Contains(err.Error(), "exceeds maximum file size") { // Handle oversized write log.Printf("Write too large for configured log size: %v", err) } } ``` -------------------------------- ### Close Logger Implementation Source: https://github.com/natefinch/lumberjack/blob/v2.0/README.md Implements the io.Closer interface by closing the current log file. Ensure this is called to release resources. ```go func (l *Logger) Close() error ``` -------------------------------- ### Logger Configuration with UTC Timestamps Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Configures the logger to use UTC for timestamps in backup filenames. This is the default behavior. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, LocalTime: false, // Use UTC (default) } // Backup: app-2024-01-15T14-30-00.000.log (UTC time) ``` -------------------------------- ### Write to Logger Source: https://github.com/natefinch/lumberjack/blob/v2.0/README.md Implements the io.Writer interface. This method handles log file rotation when the file size exceeds MaxSize. Writes larger than MaxSize will return an error. ```go func (l *Logger) Write(p []byte) (n int, err error) ``` -------------------------------- ### Integrate Lumberjack with Zap Logger Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/quick-reference.md Configure the Zap logging library to use Lumberjack for log output. Ensure Zap's core is set up to sync with a Lumberjack logger instance. ```go zapcore.AddSync(&lumberjack.Logger{...}) ``` -------------------------------- ### Signal-Based Log Rotation Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/quick-reference.md Implement log rotation triggered by operating system signals, specifically SIGHUP on Linux. This allows manual log rotation without restarting the application. ```go sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGHUP) go func() { for range sigChan { logger.Rotate() } }() ``` -------------------------------- ### Logger.Write Source: https://github.com/natefinch/lumberjack/blob/v2.0/README.md Implements the io.Writer interface. If a write would cause the log file to exceed MaxSize, the file is rotated and a new one is created. Writes larger than MaxSize return an error. ```APIDOC ## Logger.Write ### Description Implements io.Writer. If a write would cause the log file to be larger than MaxSize, the file is closed, renamed to include a timestamp of the current time, and a new log file is created using the original log file name. If the length of the write is greater than MaxSize, an error is returned. ### Signature ```go func (l *Logger) Write(p []byte) (n int, err error) ``` ``` -------------------------------- ### Integrate Lumberjack with Logrus Logger Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/quick-reference.md Configure the Logrus logging library to use Lumberjack for log output. Set Logrus's output to a Lumberjack logger instance. ```go logrus.SetOutput(&lumberjack.Logger{...}) ``` -------------------------------- ### Logger.Write Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/modules.md Writes data to the logger. This method implements the io.Writer interface, allowing the logger to be used with standard Go I/O functions and logging packages. ```APIDOC ## Logger.Write ### Description Writes data to the logger. This method implements the io.Writer interface, allowing the logger to be used with standard Go I/O functions and logging packages. ### Method `Write` ### Signature `func (l *Logger) Write(p []byte) (n int, err error)` ### Parameters #### Input - `p` ([]byte) - The byte slice containing the data to write. ### Returns - `n` (int) - The number of bytes written. - `err` (error) - An error if the write operation failed, otherwise nil. ``` -------------------------------- ### Logger Methods Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/types.md Lists the methods available on the Logger type, including `Write`, `Close`, and `Rotate`, which implement standard interfaces and provide log management functionalities. ```APIDOC ### Methods Logger provides the following methods: - `Write([]byte) (int, error)` — implements `io.Writer`, writes data and triggers rotation if needed - `Close() error` — implements `io.Closer`, closes the current log file - `Rotate() error` — manually triggers log file rotation and post-rotation cleanup ``` -------------------------------- ### Signal-Based Log Rotation (SIGHUP) Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Configure lumberjack to rotate logs when the SIGHUP signal is received. This allows for graceful log management without restarting the application. Ensure the logger is closed using defer. ```go package main import ( "log" "os" "os/signal" syscall "syscall" "gopkg.in/natefinch/lumberjack.v2" ) func main() { logger := &lumberjack.Logger{ Filename: "/var/log/server.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, } defer logger.Close() log.SetOutput(logger) // Set up signal handler for SIGHUP sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGHUP) go func() { for range sigChan { if err := logger.Rotate(); err != nil { log.Printf("Failed to rotate logs: %v", err) } else { log.Println("Logs rotated successfully") } } }() log.Println("Server started, rotate with: kill -SIGHUP ") select {} // Block forever } ``` -------------------------------- ### Deferred Logger Close Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Ensure the logger is closed to flush and close the underlying file by using `defer logger.Close()`. ```go func main() { logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, } defer logger.Close() log.SetOutput(logger) log.Println("Logging configured") } ``` -------------------------------- ### Default Lumberjack Configuration Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md When no configuration is provided, lumberjack uses default values for filename, size, backups, age, and compression. The default filename is '{processname}-lumberjack.log' in the system's temporary directory. ```go logger := &lumberjack.Logger{} log.SetOutput(logger) log.Println("Using defaults") // Results in: // - Filename: {processname}-lumberjack.log in os.TempDir() // - MaxSize: 100 MB // - MaxBackups: all (no limit) // - MaxAge: no deletion // - Compress: false ``` -------------------------------- ### Non-Blocking Cleanup with Lumberjack Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/usage-patterns.md Lumberjack's cleanup operations (compression, deletion) run asynchronously in a background goroutine, ensuring that log writes are never blocked. This is beneficial for high-throughput applications. ```go logger := &lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 50, MaxBackups: 100, // Many backups MaxAge: 365, // Long retention Compress: true, // Enable compression } // Even with large cleanup operations, writes complete quickly // because cleanup happens in background goroutine log.SetOutput(logger) for i := 0; i < 1000000; i++ { log.Printf("Message %d\n", i) // Never blocked by cleanup } ``` -------------------------------- ### Rotate Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/api-reference/logger.md Rotate closes the existing log file and immediately creates a new one. This is a helper function for applications that want to initiate rotations outside of the normal rotation rules, such as in response to a SIGHUP signal. After rotation, post-rotation processing is initiated, including compression of old log files (if enabled) and removal of old log files according to MaxBackups and MaxAge constraints. ```APIDOC ## func (*Logger) Rotate ### Description Rotate closes the existing log file and immediately creates a new one. This is a helper function for applications that want to initiate rotations outside of the normal rotation rules, such as in response to a SIGHUP signal. After rotation, post-rotation processing is initiated, including compression of old log files (if enabled) and removal of old log files according to MaxBackups and MaxAge constraints. ### Return Values | Value | Type | Description | |-------|------|-------------| | err | error | Error if closing current file or opening new file fails | ### Example ```go package main import ( "log" "os" "os/signal" "syscall" "gopkg.in/natefinch/lumberjack.v2" ) func main() { l := &lumberjack.Logger{ Filename: "/var/log/myapp/server.log", MaxSize: 100, MaxBackups: 3, MaxAge: 28, } defer l.Close() log.SetOutput(l) // Set up signal handling for graceful rotation sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGHUP) go func() { for range sigChan { if err := l.Rotate(); err != nil { log.Printf("Failed to rotate log: %v", err) } } }() // Application continues... log.Println("Server running") select {} } ``` ``` -------------------------------- ### Handle Linux Ownership Rotation Failure Source: https://github.com/natefinch/lumberjack/blob/v2.0/_autodocs/errors.md On Linux, if the log file is owned by a different user and the process lacks permission to change ownership, rotation will fail. This snippet shows how to log such an error. ```go // On Linux, if log file is owned by a different user, // and the process doesn't have permission to chown, // rotation will fail l := &lumberjack.Logger{Filename: "/var/log/app.log"} if err := l.Rotate(); err != nil { log.Printf("Rotation failed (ownership issue?): %v", err) } ```