Documentation ¶
Overview ¶
Package logger provides a rolling logger.
Note that this is v2.0 of lumberjack, and should be imported using gopkg.in thusly:
import "gopkg.in/natefinch/lumberjack.v2"
The package name remains simply lumberjack, and the code resides at https://github.com/natefinch/lumberjack under the v2.0 branch.
Lumberjack is intended to be one part of a logging infrastructure. It is not an all-in-one solution, but instead is a pluggable component at the bottom of the logging stack that simply controls the files to which logs are written.
Lumberjack plays well with any logging package that can write to an io.Writer, including the standard library's log package.
Lumberjack assumes that only one process is writing to the output files. Using the same lumberjack configuration from multiple processes on the same machine will result in improper behavior.
Example ¶
To use lumberjack with the standard library's log package, just pass it into the SetOutput function when your application starts.
log.SetOutput(&RollingFile{ Filename: "/var/log/myapp/foo.log", MaxSize: 500, // megabytes MaxBackups: 3, MaxAge: 28, // days Compress: true, // disabled by default })
Output:
Index ¶
- Constants
- func CopyFields(fields map[string]interface{}) []interface{}
- func Debug(args ...interface{})
- func Debugf(template string, args ...interface{})
- func Debugw(msg string, keysAndValues ...interface{})
- func Error(args ...interface{})
- func Errorf(template string, args ...interface{})
- func Errorw(msg string, keysAndValues ...interface{})
- func Fatal(args ...interface{})
- func Fatalf(template string, args ...interface{})
- func Fatalw(msg string, keysAndValues ...interface{})
- func Info(args ...interface{})
- func Infof(template string, args ...interface{})
- func Infow(msg string, keysAndValues ...interface{})
- func SetLevel(lv Level)
- func SpanID(ctx context.Context) string
- func Sync() error
- func TraceID(ctx context.Context) string
- func Warn(args ...interface{})
- func Warnf(template string, args ...interface{})
- func Warnw(msg string, keysAndValues ...interface{})
- type Encoder
- type Level
- type Logger
- type Logging
- func (l *Logging) Clone() *Logging
- func (l *Logging) Debug(args ...interface{})
- func (l *Logging) Debugf(template string, args ...interface{})
- func (l *Logging) Debugw(msg string, keysAndValues ...interface{})
- func (l *Logging) Error(args ...interface{})
- func (l *Logging) Errorf(template string, args ...interface{})
- func (l *Logging) Errorw(msg string, keysAndValues ...interface{})
- func (l *Logging) Fatal(args ...interface{})
- func (l *Logging) Fatalf(template string, args ...interface{})
- func (l *Logging) Fatalw(msg string, keysAndValues ...interface{})
- func (l *Logging) Info(args ...interface{})
- func (l *Logging) Infof(template string, args ...interface{})
- func (l *Logging) Infow(msg string, keysAndValues ...interface{})
- func (l *Logging) Options() Options
- func (l *Logging) SetLevel(lv Level)
- func (l *Logging) Sync() error
- func (l *Logging) Warn(args ...interface{})
- func (l *Logging) Warnf(template string, args ...interface{})
- func (l *Logging) Warnw(msg string, keysAndValues ...interface{})
- func (l *Logging) WithCallDepth(callDepth int) Logger
- func (l *Logging) WithContext(ctx context.Context) Logger
- func (l *Logging) WithFields(fields map[string]any) Logger
- type Option
- func Fields(fields map[string]any) Option
- func WithCallerSkip(callerSkip int) Option
- func WithCompress(compress bool) Option
- func WithEncoder(encoder Encoder) Option
- func WithEncoderConfig(encoderConfig zapcore.EncoderConfig) Option
- func WithFilename(filename string) Option
- func WithLevel(level Level) Option
- func WithLocalTime(localTime bool) Option
- func WithMaxAge(maxAge int) Option
- func WithMaxBackups(maxBackups int) Option
- func WithMaxSize(maxSize int) Option
- func WithMode(mode string) Option
- func WithNamespace(namespace string) Option
- func WithRoll(roll RollingFormat) Option
- func WithWriter(w io.Writer) Option
- type Options
- type RollingFile
- type RollingFormat
- type WrappedWriteSyncer
Examples ¶
Constants ¶
const ( MonthlyRolling RollingFormat = "200601" DailyRolling = "20060102" HourlyRolling = "2006010215" MinutelyRolling = "200601021504" SecondlyRolling = "20060102150405" )
Variables ¶
This section is empty.
Functions ¶
func CopyFields ¶
func CopyFields(fields map[string]interface{}) []interface{}
Types ¶
type Level ¶
const ( // DebugLevel logs are typically voluminous, and are usually disabled in // production. DebugLevel Level = iota - 1 // InfoLevel is the default logging priority. InfoLevel // WarnLevel logs are more important than Info, but don't need individual // human review. WarnLevel // ErrorLevel logs are high-priority. If an application is running smoothly, // it shouldn't generate any error-level logs. ErrorLevel // DPanicLevel logs are particularly important errors. In development the // logger panics after writing the message. DPanicLevel // PanicLevel logs a message, then panics. PanicLevel // FatalLevel logs a message, then calls os.Exit(1). FatalLevel // InvalidLevel is an invalid value for Level. // // Core implementations may panic if they see messages of this level. InvalidLevel = _maxLevel + 1 )
type Logger ¶
type Logger interface { // SetLevel set logger level SetLevel(lv Level) // WithContext with context WithContext(ctx context.Context) Logger // WithFields set fields to always be logged WithFields(fields map[string]any) Logger // WithCallDepth with logger call depth. WithCallDepth(callDepth int) Logger // Debug uses fmt.Sprint to construct and log a message. Debug(args ...interface{}) // Info uses fmt.Sprint to construct and log a message. Info(args ...interface{}) // Warn uses fmt.Sprint to construct and log a message. Warn(args ...interface{}) // Error uses fmt.Sprint to construct and log a message. Error(args ...interface{}) // Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit. Fatal(args ...interface{}) // Debugf uses fmt.Sprintf to log a templated message. Debugf(template string, args ...interface{}) // Infof uses fmt.Sprintf to log a templated message. Infof(template string, args ...interface{}) // Warnf uses fmt.Sprintf to log a templated message. Warnf(template string, args ...interface{}) // Errorf uses fmt.Sprintf to log a templated message. Errorf(template string, args ...interface{}) // Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit. Fatalf(template string, args ...interface{}) // Debugw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. // // When debug-level logging is disabled, this is much faster than // s.With(keysAndValues).Debug(msg) Debugw(msg string, keysAndValues ...interface{}) // Infow logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. Infow(msg string, keysAndValues ...interface{}) // Warnw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. Warnw(msg string, keysAndValues ...interface{}) // Errorw logs a message with some additional context. The variadic key-value // pairs are treated as they are in With. Errorw(msg string, keysAndValues ...interface{}) // Fatalw logs a message with some additional context, then calls os.Exit. The // variadic key-value pairs are treated as they are in With. Fatalw(msg string, keysAndValues ...interface{}) // Sync logger sync Sync() error }
Logger is the interface for Logger types
func WithCallDepth ¶
WithCallDepth returns a shallow copy of l with its caller skip
func WithContext ¶
WithContext returns a shallow copy of l with its context changed to ctx. The provided ctx must be non-nil.
func WithFields ¶
WithFields is a helper to create a []interface{} of key-value pairs.
type Logging ¶
type Logging struct {
// contains filtered or unexported fields
}
func (*Logging) WithCallDepth ¶
type Option ¶
type Option func(o *Options)
func WithCallerSkip ¶
WithCallerSkip Setter function to set the caller skip value.
func WithCompress ¶
WithCompress Setter function to set the compress option.
func WithEncoder ¶
WithEncoder Setter function to set the encoder.
func WithEncoderConfig ¶
func WithEncoderConfig(encoderConfig zapcore.EncoderConfig) Option
WithEncoderConfig Setter function to set the encoder config.
func WithFilename ¶
WithFilename Setter function to set the log filename.
func WithLocalTime ¶
WithLocalTime Setter function to set the local time option.
func WithMaxAge ¶
WithMaxAge Setter function to set the maximum log age.
func WithMaxBackups ¶
WithMaxBackups Setter function to set the maximum number of log backups.
func WithMaxSize ¶
WithMaxSize Setter function to set the maximum log size.
func WithNamespace ¶
WithNamespace Setter function to set the namespace.
func WithRoll ¶
func WithRoll(roll RollingFormat) Option
WithRoll Setter function to set the rolling format.
func WithWriter ¶
type RollingFile ¶
type RollingFile struct { // Filename is the file to write logs to. Backup log files will be retained // in the same directory. It uses <processname>-lumberjack.log in // os.TempDir() if empty. Filename string `json:"filename" yaml:"filename"` // Rolling is the format of the rolling file Rolling RollingFormat `json:"rolling" yaml:"rolling"` // MaxSize is the maximum size in megabytes of the log file before it gets // rotated. It defaults to 100 megabytes. MaxSize int `json:"maxsize" yaml:"maxsize"` // MaxAge is the maximum number of days to retain old log files based on the // timestamp encoded in their filename. Note that a day is defined as 24 // hours and may not exactly correspond to calendar days due to daylight // savings, leap seconds, etc. The default is not to remove old log files // based on age. MaxAge int `json:"maxage" yaml:"maxage"` // MaxBackups is the maximum number of old log files to retain. The default // is to retain all old log files (though MaxAge may still cause them to get // deleted.) MaxBackups int `json:"maxbackups" yaml:"maxbackups"` // LocalTime determines if the time used for formatting the timestamps in // backup files is the computer's local time. The default is to use UTC // time. LocalTime bool `json:"localtime" yaml:"localtime"` // Compress determines if the rotated log files should be compressed // using gzip. The default is not to perform compression. Compress bool `json:"compress" yaml:"compress"` // contains filtered or unexported fields }
RollingFile is an io.WriteCloser that writes to the specified filename.
RollingFile opens or creates the logfile on first Write. If the file exists and is less than MaxSize megabytes, lumberjack will open and append to that file. If the file exists and its size is >= MaxSize megabytes, the file is renamed by putting the current time in a timestamp in the name immediately before the file's extension (or the end of the filename if there's no extension). A new log file is then created using original filename.
Whenever a write would cause the current log file exceed MaxSize megabytes, the current file is closed, renamed, and a new log file created with the original name. Thus, the filename you give RollingFile is always the "current" log file.
Backups use the log file name given to RollingFile, in the form `name-timestamp.ext` where name is the filename without the extension, timestamp is the time at which the log was rotated formatted with the time.Time format of `2006-01-02T15-04-05.000` and the extension is the original extension. For example, if your RollingFile.Filename is `/var/log/foo/server.log`, a backup created at 6:30pm on Nov 11 2016 would use the filename `/var/log/foo/server-2016-11-04T18-30-00.000.log`
Cleaning Up Old Log Files ¶
Whenever a new logfile gets created, old log files may be deleted. The most recent files according to the encoded timestamp will be retained, up to a number equal to MaxBackups (or all of them if MaxBackups is 0). Any files with an encoded timestamp older than MaxAge days are deleted, regardless of MaxBackups. Note that the time encoded in the timestamp is the rotation time, which may differ from the last time that file was written to.
If MaxBackups and MaxAge are both 0, no old log files will be deleted.
func NewRollingFile ¶
func NewRollingFile(filename string, rolling RollingFormat, maxSize int, maxAge int, maxBackups int, localTime bool, compress bool) *RollingFile
NewRollingFile creates a new RollingFile.
func (*RollingFile) Close ¶
func (l *RollingFile) Close() error
Close implements io.Closer, and closes the current logfile.
func (*RollingFile) Rotate ¶
func (l *RollingFile) Rotate() error
Rotate causes RollingFile to close the existing log file and immediately create 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 SIGHUP. After rotating, this initiates compression and removal of old log files according to the configuration.
func (*RollingFile) Sync ¶
func (l *RollingFile) Sync() error
func (*RollingFile) Write ¶
func (l *RollingFile) Write(p []byte) (n int, err error)
Write 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.
type WrappedWriteSyncer ¶
type WrappedWriteSyncer struct {
// contains filtered or unexported fields
}
WrappedWriteSyncer is a helper struct implementing zapcore.WriteSyncer to wrap a standard os.Stdout handle, giving control over the WriteSyncer's Sync() function. Sync() results in an error on Windows in combination with os.Stdout ("sync /dev/stdout: The handle is invalid."). WrappedWriteSyncer simply does nothing when Sync() is called by Zap.
func (WrappedWriteSyncer) Sync ¶
func (mws WrappedWriteSyncer) Sync() error