logger

package module
v1.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 24, 2024 License: MIT Imports: 18 Imported by: 29

README

go 日志模块

基础日志模块,基于 uber.zap 封装

日志级别

// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel = iota + 1
// InfoLevel is the default logging priority.
// General operational entries about what's going on inside the application.
InfoLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
ErrorLevel
// FatalLevel level. Logs and then calls `logger.Exit(1)`. highest level of severity.
FatalLevel

低于级别的日志不会输出,高于级别的日志会输出到对应的文件,建议 开发环境 日志级别设置为 DEBUG, 线上环境 日志级别设置为 INFO

打印日志方法

// Logger is the interface for Logger types
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
}

简单使用

使用日志的时候注意尽量避免使用 Fatal 级别的日志,虽然提供了,但是不建议使用,使用 Fatal 记录消息后,直接调用 os.Exit(1),这意味着: 在其他 goroutine defer 语句不会被执行; 各种 buffers 不会被 flush,包括日志的; 临时文件或者目录不会被移除; 不要使用 fatal 记录日志,而是向调用者返回错误。如果错误一直持续到 main.main。main.main 那就是在退出之前做处理任何清理操作的正确位置。

日志初始化
logger.InitLogger(New(
    WithPath("../logs"),
    WithLevel(DebugLevel),
    WithMode(ConsoleMode),
    Fields(map[string]interface{}{
    "app_id":      "nextmicro",
    "instance_id": "JeffreyBool",
    }),
))

上面会覆盖日志默认的行为,因为方便使用,默认调用就会初始化

各种级别日志输出
func TestDebug(t *testing.T) {
	logger.Debug("test debug logger")
	logger.Debugf("debug test time:%d", time.Now().Unix())
	logger.Sync()
}

func TestInfo(t *testing.T) {
	logger.Info("测试日志")
	logger.Infof("name:%s, age:%d", "pandatv", 14)
	logger.Infow("我们都是中国人", "age", 18, "name", "zhanggaoyuan")
    logger.Sync()
}

func TestWarn(t *testing.T) {
	logger.Warn("test warn logger")
	logger.Warnf("warn test time:%d", time.Now().Unix())
    logger.Sync()
}

func TestError(t *testing.T) {
	logger.Error("test error logger")
	logger.Errorf("error test time:%d", time.Now().Unix())
    logger.Sync()
}
日志多实例使用

多实例日志必须设置 WithFilename(xxx) 和普通日志区分,这种日志不需要指定级别,全部会输出到一个文件中

slow := New(
    WithPath("../logs"),
    WithMode(FileMode),
    WithFilename("slow"),
    WithFields(map[string]interface{}{
    "app_id":      "mt",
    "instance_id": "JeffreyBool",
    }),
)

slow.Info(msg)

需要外部自己保存日志的对象信息

注意事项

  • 不要使用 Fatal 级别日志
  • 日志使用完毕后一定要显式调用 Sync() 函数将日志落盘

Documentation

Index

Constants

View Source
const (
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel = iota + 1
	// InfoLevel is the default logging priority.
	// General operational entries about what's going on inside the application.
	InfoLevel
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	ErrorLevel
	// FatalLevel level. Logs and then calls `logger.Exit(1)`. highest level of severity.
	FatalLevel
)
View Source
const (
	FileMode    = "file"
	ConsoleMode = "console"
)

Variables

View Source
var ErrLogFileClosed = errors.New("error: log file closed")

ErrLogFileClosed is an error that indicates the log file is already closed.

View Source
var (
	// ErrLogPathNotSet is an error that indicates the log path is not set.
	ErrLogPathNotSet = errors.New("log path must be set")
)

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 NewNonColorable added in v1.0.6

func NewNonColorable(w zapcore.WriteSyncer) io.Writer

NewNonColorable returns new instance of Writer which removes escape sequence from Writer.

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 AnyType added in v1.0.6

type AnyType = any

AnyType can be used to hold any type.

type DailyRotateRule added in v1.0.6

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

A DailyRotateRule is a rule to daily rotate the log files.

func (*DailyRotateRule) BackupFileName added in v1.0.6

func (r *DailyRotateRule) BackupFileName() string

BackupFileName returns the backup filename on rotating.

func (*DailyRotateRule) MarkRotated added in v1.0.6

func (r *DailyRotateRule) MarkRotated()

MarkRotated marks the rotated time of r to be the current time.

func (*DailyRotateRule) OutdatedFiles added in v1.0.6

func (r *DailyRotateRule) OutdatedFiles() []string

OutdatedFiles returns the files that exceeded the keeping days.

func (*DailyRotateRule) ShallRotate added in v1.0.6

func (r *DailyRotateRule) ShallRotate(_ int64) bool

ShallRotate checks if the file should be rotated.

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 FileSystem added in v1.0.6

type FileSystem interface {
	Close(closer io.Closer) error
	Copy(writer io.Writer, reader io.Reader) (int64, error)
	Create(name string) (*os.File, error)
	Open(name string) (*os.File, error)
	Remove(name string) error
}

type HourRotateRule added in v1.0.6

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

HourRotateRule a rotation rule that make the log file rotated base on hour

func NewHourRotateRule added in v1.0.6

func NewHourRotateRule(filename, delimiter string, hours int, gzip bool) *HourRotateRule

NewHourRotateRule new a hour rotate rule

func (*HourRotateRule) BackupFileName added in v1.0.6

func (r *HourRotateRule) BackupFileName() string

BackupFileName returns the backup filename on rotating.

func (*HourRotateRule) MarkRotated added in v1.0.6

func (r *HourRotateRule) MarkRotated()

MarkRotated marks the rotated time of r to be the current time.

func (*HourRotateRule) OutdatedFiles added in v1.0.6

func (r *HourRotateRule) OutdatedFiles() []string

OutdatedFiles returns the files that exceeded the keeping hours.

func (*HourRotateRule) ShallRotate added in v1.0.6

func (r *HourRotateRule) ShallRotate(_ int64) bool

ShallRotate checks if the file should be rotated.

type Level

type Level int8

func ParseLevel added in v1.0.3

func ParseLevel(s string) Level

ParseLevel parses a level string into a logger Level value.

func (Level) Enabled added in v1.0.3

func (l Level) Enabled(lvl Level) bool

Enabled returns true if the given level is at or above this level.

func (Level) String added in v1.0.3

func (l Level) String() string

type LevelEnablerFunc added in v1.0.3

type LevelEnablerFunc func(zapcore.Level) bool

LevelEnablerFunc is a convenient way to implement zapcore.LevelEnabler with an anonymous function.

It's particularly useful when splitting log output between different outputs (e.g., standard error and standard out). For sample code, see the package-level AdvancedConfiguration example.

func (LevelEnablerFunc) Enabled added in v1.0.3

func (f LevelEnablerFunc) Enabled(lvl zapcore.Level) bool

Enabled calls the wrapped function.

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) LevelEnablerFunc added in v1.0.3

func (l *Logging) LevelEnablerFunc(level zapcore.Level) LevelEnablerFunc

func (*Logging) Options

func (l *Logging) Options() Options

func (*Logging) SetLevel

func (l *Logging) SetLevel(lv Level)

func (*Logging) Sync

func (l *Logging) Sync() (err 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 NonColorable added in v1.0.6

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

NonColorable holds writer but removes escape sequence.

func (*NonColorable) Sync added in v1.0.6

func (w *NonColorable) Sync() error

Sync flushes the buffer.

func (*NonColorable) Write added in v1.0.6

func (w *NonColorable) Write(data []byte) (n int, err error)

Write writes data on console

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 WithKeepDays added in v1.0.6

func WithKeepDays(keepDays int) Option

func WithKeepHours added in v1.0.6

func WithKeepHours(keepHours int) Option

func WithLevel

func WithLevel(level Level) Option

WithLevel Setter function to set the logging level.

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 WithPath added in v1.0.3

func WithPath(path string) Option

WithPath Setter function to set the log path.

func WithRotation added in v1.0.6

func WithRotation(rotation string) Option

func WithWriter

func WithWriter(w io.Writer) Option

type Options

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

type PlaceholderType added in v1.0.6

type PlaceholderType = struct{}

PlaceholderType represents a placeholder type.

var Placeholder PlaceholderType

Placeholder is a placeholder object that can be used globally.

type RotateLogger added in v1.0.6

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

A RotateLogger is a Logger that can rotate log files with given rules.

func NewRotateLogger added in v1.0.6

func NewRotateLogger(filename string, rule RotateRule, compress bool) (*RotateLogger, error)

NewRotateLogger returns a RotateLogger with given filename and rule, etc.

func (*RotateLogger) Close added in v1.0.6

func (l *RotateLogger) Close() (err error)

Close closes l.

func (*RotateLogger) Sync added in v1.0.6

func (l *RotateLogger) Sync() error

func (*RotateLogger) Write added in v1.0.6

func (l *RotateLogger) Write(data []byte) (int, error)

type RotateRule added in v1.0.6

type RotateRule interface {
	BackupFileName() string
	MarkRotated()
	OutdatedFiles() []string
	ShallRotate(size int64) bool
}

A RotateRule interface is used to define the log rotating rules.

func DefaultRotateRule added in v1.0.6

func DefaultRotateRule(filename, delimiter string, days int, gzip bool) RotateRule

DefaultRotateRule is a default log rotating rule, currently DailyRotateRule.

func NewSizeLimitRotateRule added in v1.0.6

func NewSizeLimitRotateRule(filename, delimiter string, days, maxSize, maxBackups int, gzip bool) RotateRule

NewSizeLimitRotateRule returns the rotation rule with size limit

type SizeLimitRotateRule added in v1.0.6

type SizeLimitRotateRule struct {
	DailyRotateRule
	// contains filtered or unexported fields
}

SizeLimitRotateRule a rotation rule that make the log file rotated base on size

func (*SizeLimitRotateRule) BackupFileName added in v1.0.6

func (r *SizeLimitRotateRule) BackupFileName() string

func (*SizeLimitRotateRule) MarkRotated added in v1.0.6

func (r *SizeLimitRotateRule) MarkRotated()

func (*SizeLimitRotateRule) OutdatedFiles added in v1.0.6

func (r *SizeLimitRotateRule) OutdatedFiles() []string

func (*SizeLimitRotateRule) ShallRotate added in v1.0.6

func (r *SizeLimitRotateRule) ShallRotate(size int64) bool

type StandardFileSystem added in v1.0.6

type StandardFileSystem struct{}

func (StandardFileSystem) Close added in v1.0.6

func (fs StandardFileSystem) Close(closer io.Closer) error

func (StandardFileSystem) Copy added in v1.0.6

func (fs StandardFileSystem) Copy(writer io.Writer, reader io.Reader) (int64, error)

func (StandardFileSystem) Create added in v1.0.6

func (fs StandardFileSystem) Create(name string) (*os.File, error)

func (StandardFileSystem) Open added in v1.0.6

func (fs StandardFileSystem) Open(name string) (*os.File, error)

func (StandardFileSystem) Remove added in v1.0.6

func (fs StandardFileSystem) Remove(name string) error

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)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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