logger

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 9, 2023 License: MIT Imports: 18 Imported by: 29

README

logger

logger kit

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

Examples

Constants

View Source
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{}

func Debug

func Debug(args ...interface{})

func Debugf

func Debugf(template string, args ...interface{})

func Debugw

func Debugw(msg string, keysAndValues ...interface{})

func Error

func Error(args ...interface{})

func Errorf

func Errorf(template string, args ...interface{})

func Errorw

func Errorw(msg string, keysAndValues ...interface{})

func Fatal

func Fatal(args ...interface{})

func Fatalf

func Fatalf(template string, args ...interface{})

func Fatalw

func Fatalw(msg string, keysAndValues ...interface{})

func Info

func Info(args ...interface{})

func Infof

func Infof(template string, args ...interface{})

func Infow

func Infow(msg string, keysAndValues ...interface{})

func SetLevel

func SetLevel(lv Level)

SetLevel set logger level

func SpanID

func SpanID(ctx context.Context) string

SpanID returns a spanid valuer.

func Sync

func Sync() error

func TraceID

func TraceID(ctx context.Context) string

TraceID returns a traceid valuer.

func Warn

func Warn(args ...interface{})

func Warnf

func Warnf(template string, args ...interface{})

func Warnw

func Warnw(msg string, keysAndValues ...interface{})

Types

type Encoder

type Encoder string
const (
	JsonEncoder    Encoder = "json"
	ConsoleEncoder Encoder = "console"
)

func (Encoder) IsConsole

func (e Encoder) IsConsole() bool

IsConsole Whether console encoder.

func (Encoder) IsJson

func (e Encoder) IsJson() bool

IsJson Whether json encoder.

func (Encoder) String

func (e Encoder) String() string

type Level

type Level zapcore.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
)

func (Level) Level

func (l Level) Level() zapcore.Level

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

var DefaultLogger Logger = New()

DefaultLogger is default logger.

func WithCallDepth

func WithCallDepth(callDepth int) Logger

WithCallDepth returns a shallow copy of l with its caller skip

func WithContext

func WithContext(ctx context.Context) Logger

WithContext returns a shallow copy of l with its context changed to ctx. The provided ctx must be non-nil.

func WithFields

func WithFields(fields map[string]interface{}) Logger

WithFields is a helper to create a []interface{} of key-value pairs.

type Logging

type Logging struct {
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *Logging

func (*Logging) Clone

func (l *Logging) Clone() *Logging

func (*Logging) Debug

func (l *Logging) Debug(args ...interface{})

func (*Logging) Debugf

func (l *Logging) Debugf(template string, args ...interface{})

func (*Logging) Debugw

func (l *Logging) Debugw(msg string, keysAndValues ...interface{})

func (*Logging) Error

func (l *Logging) Error(args ...interface{})

func (*Logging) Errorf

func (l *Logging) Errorf(template string, args ...interface{})

func (*Logging) Errorw

func (l *Logging) Errorw(msg string, keysAndValues ...interface{})

func (*Logging) Fatal

func (l *Logging) Fatal(args ...interface{})

func (*Logging) Fatalf

func (l *Logging) Fatalf(template string, args ...interface{})

func (*Logging) Fatalw

func (l *Logging) Fatalw(msg string, keysAndValues ...interface{})

func (*Logging) Info

func (l *Logging) Info(args ...interface{})

func (*Logging) Infof

func (l *Logging) Infof(template string, args ...interface{})

func (*Logging) Infow

func (l *Logging) Infow(msg string, keysAndValues ...interface{})

func (*Logging) Options

func (l *Logging) Options() Options

func (*Logging) SetLevel

func (l *Logging) SetLevel(lv Level)

func (*Logging) Sync

func (l *Logging) Sync() error

func (*Logging) Warn

func (l *Logging) Warn(args ...interface{})

func (*Logging) Warnf

func (l *Logging) Warnf(template string, args ...interface{})

func (*Logging) Warnw

func (l *Logging) Warnw(msg string, keysAndValues ...interface{})

func (*Logging) WithCallDepth

func (l *Logging) WithCallDepth(callDepth int) Logger

func (*Logging) WithContext

func (l *Logging) WithContext(ctx context.Context) Logger

func (*Logging) WithFields

func (l *Logging) WithFields(fields map[string]any) Logger

type Option

type Option func(o *Options)

func Fields

func Fields(fields map[string]any) Option

Fields Setter function to set the logger fields.

func WithCallerSkip

func WithCallerSkip(callerSkip int) Option

WithCallerSkip Setter function to set the caller skip value.

func WithCompress

func WithCompress(compress bool) Option

WithCompress Setter function to set the compress option.

func WithEncoder

func WithEncoder(encoder Encoder) Option

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

func WithFilename(filename string) Option

WithFilename Setter function to set the log filename.

func WithLevel

func WithLevel(level Level) Option

WithLevel Setter function to set the logging level.

func WithLocalTime

func WithLocalTime(localTime bool) Option

WithLocalTime Setter function to set the local time option.

func WithMaxAge

func WithMaxAge(maxAge int) Option

WithMaxAge Setter function to set the maximum log age.

func WithMaxBackups

func WithMaxBackups(maxBackups int) Option

WithMaxBackups Setter function to set the maximum number of log backups.

func WithMaxSize

func WithMaxSize(maxSize int) Option

WithMaxSize Setter function to set the maximum log size.

func WithMode

func WithMode(mode string) Option

WithMode Setter function to set the logging mode.

func WithNamespace

func WithNamespace(namespace string) Option

WithNamespace Setter function to set the namespace.

func WithRoll

func WithRoll(roll RollingFormat) Option

WithRoll Setter function to set the rolling format.

func WithWriter

func WithWriter(w io.Writer) Option

type Options

type Options struct {
	// contains filtered or unexported fields
}

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 RollingFormat

type RollingFormat string

RollingFormat is the format of the rolling file

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

func (WrappedWriteSyncer) Write

func (mws WrappedWriteSyncer) Write(p []byte) (n int, err error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL