log

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2023 License: MIT Imports: 8 Imported by: 0

README

日志组件说明

日志组件分为 Logger 跟 Writer 两块,对第三方库进行二次封装提供统一接口。

logger包说明

  • logger包是一组实现Logger接口的组件。
type Logger interface {
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})
	Info(args ...interface{})
	Infof(format string, args ...interface{})
	Warn(args ...interface{})
	Warnf(format string, args ...interface{})
	Error(args ...interface{})
	Errorf(format string, args ...interface{})
	Trace(args ...interface{})
	Tracef(format string, args ...interface{})
	Panic(args ...interface{})
	Panicf(format string, args ...interface{})
	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})

	WithField(key string, value interface{}) Logger
	WithFields(fields map[string]interface{}) Logger

	SetLogLevel(level Level) error
}

writer包说明

  • writer包是一组实现io.Writer接口的组件。
type Writer interface {
	Write(p []byte) (n int, err error)
}

Option

    // log options    

	// EncoderConfig 说明
	EncoderConfig := EncoderConfig{}
	EncoderConfig.MessageKey = "msg" // MessageKey

	EncoderConfig.LevelKey = "level"                  // LevelKey
	EncoderConfig.EncodeLevel = LowercaseLevelEncoder // 具体请看 LevelEncoder

	EncoderConfig.TimeKey = "@timestamp"               // TimeKey
	EncoderConfig.EncodeTime = RFC3339MilliTimeEncoder // 具体请看 TimeEncoder,默认RFC3339TimeEncoder

	// caller
	// note: CallerKey不为空 且 设置AddCaller 才会输出
	EncoderConfig.CallerKey = "caller"             // CallerKey
	EncoderConfig.EncodeCaller = FullCallerEncoder // CallerEncoder,默认FullCallerEncoder
	AddCaller()                                    // 显示日志调用者的文件名跟行号,默认不打开
	AddCallerSkip(1)                               // 跳过多少级caller 

	// Stacktrace
	// note: StacktraceKey不为空 且 达到Stacktrace设置的级别 才会输出
	EncoderConfig.StacktraceKey = "detail" // StacktraceKey ,配合 AddStacktrace 使用
	AddStacktrace(ErrorLevel)              // 默认ErrorLevel

	WithEncoderCfg(EncoderConfig) // 也可以使用默认配置 WithEncoderCfg(NewEncoderConfig())
	WithEncoder(JSONEncoder)      // 具体请看 Encoder,默认JSONEncoder

	WithLevelEnabler(DebugLevel)                 // 可选,设置日志输出级别,默认DebugLevel
	WithWriter(os.Stdout)                        // 可选,设置日志的wirter
	Fields(map[string]interface{}{"wong": "yes"}) // 可选,增加字段到日志输出
	ErrorOutput(os.Stderr)                       // 可选,ErrorLevel及之后的日志级别将往这里输出

Example

// Logger
opts := []Option{ // 根据实际需求添加option
    WithLevelEnabler(DebugLevel),
    WithEncoderCfg(NewEncoderConfig()), 
}

l, err := New(ZapLogger, opts...)
l.Info("Hello World!")

// Writer
wopts := []rotate.Option{ // 根据实际需求添加option
    rotate.WithLogDir("/data/log"),
    rotate.WithLogSubDir("info"),
}
w := NewWriter(wopts...)
w.Write([]byte("Hello World!"))

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Info    func(args ...interface{})
	Warn    func(args ...interface{})
	Error   func(args ...interface{})
	Fatal   func(args ...interface{})
	Notice  func(args ...interface{})
	Debug   func(args ...interface{})
	Infof   func(format string, args ...interface{})
	Warnf   func(format string, args ...interface{})
	Errorf  func(format string, args ...interface{})
	Fatalf  func(format string, args ...interface{})
	Noticef func(format string, args ...interface{})
	Debugf  func(format string, args ...interface{})

	WithField   func(key string, value interface{}) Logger
	WithFields  func(fields map[string]interface{}) Logger
	WithTraceId func(ctx context.Context) Logger
)

Functions

func Setup

func Setup(opts ...Option)

Types

type CallerEncoder

type CallerEncoder int

FullCallerEncoder serializes a caller in /full/path/to/package/file:line format. ShortCallerEncoder serializes a caller in package/file:line format, trimming all but the final directory from the full path.

const (
	FullCallerEncoder CallerEncoder = iota
	ShortCallerEncoder
)

type Encoder

type Encoder int
const (
	JSONEncoder Encoder = iota
	ConsoleEncoder
)

type EncoderConfig

type EncoderConfig struct {
	MessageKey    string
	LevelKey      string
	EncodeLevel   LevelEncoder
	TimeKey       string
	EncodeTime    TimeEncoder
	CallerKey     string
	EncodeCaller  CallerEncoder
	StacktraceKey string
}

func NewEncoderConfig

func NewEncoderConfig() EncoderConfig

type Level

type Level int
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
	// PanicLevel logs a message, then panics.
	PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel
	// NoticeLevel logs a message, then make a log alert
	NoticeLevel

	TraceLevel = DebugLevel
)

func AllLevels

func AllLevels() []Level

func (Level) Enabled

func (l Level) Enabled(lvl Level) bool

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

func (Level) String

func (l Level) String() string

String returns a lower-case ASCII representation of the log level.

type LevelEnabler

type LevelEnabler interface {
	Enabled(Level) bool
}

LevelEnabler decides whether a given logging level is enabled when logging a message.

Enablers are intended to be used to implement deterministic filters; concerns like sampling are better implemented as a Core.

Each concrete Level value implements a static LevelEnabler which returns true for itself and all higher logging levels. For example WarnLevel.Enabled() will return true for WarnLevel, ErrorLevel, DPanicLevel, PanicLevel, and FatalLevel, but return false for InfoLevel and DebugLevel.

type LevelEncoder

type LevelEncoder int

LowercaseLevelEncoder serializes a Level to a lowercase string. For example, InfoLevel is serialized to "info". CapitalLevelEncoder serializes a Level to an all-caps string. For example, InfoLevel is serialized to "INFO".

const (
	LowercaseLevelEncoder LevelEncoder = iota
	CapitalLevelEncoder
)

type Logger

type Logger interface {
	Debug(args ...interface{})
	Debugf(format string, args ...interface{})

	Info(args ...interface{})
	Infof(format string, args ...interface{})

	Warn(args ...interface{})
	Warnf(format string, args ...interface{})

	Error(args ...interface{})
	Errorf(format string, args ...interface{})

	Trace(args ...interface{})
	Tracef(format string, args ...interface{})

	Panic(args ...interface{})
	Panicf(format string, args ...interface{})

	Fatal(args ...interface{})
	Fatalf(format string, args ...interface{})

	Notice(args ...interface{})
	Noticef(format string, args ...interface{})

	WithField(key string, value interface{}) Logger
	WithFields(fields map[string]interface{}) Logger

	WithTraceId(ctx context.Context) Logger

	SetLogLevel(level Level) error

	LogLevel() Level
}

func GetLogger

func GetLogger() Logger

GetLogger return defaultLogger

func New

func New(Type LoggerType, opts ...Option) (Logger, error)

type LoggerType

type LoggerType int
const (
	ZapLogger LoggerType = iota
)

type MockCheckWriteHook

type MockCheckWriteHook struct{}

MockCheckWriteHook should be careful for test, should be recover

func (*MockCheckWriteHook) OnWrite

func (mcw *MockCheckWriteHook) OnWrite(e *zapcore.CheckedEntry, _ []zapcore.Field)

type Option

type Option interface {
	// contains filtered or unexported methods
}

func AddCaller

func AddCaller() Option

AddCaller configures the Logger to annotate each message with the filename and line number of logger's caller.

func AddCallerSkip

func AddCallerSkip(skip int) Option

AddCallerSkip increases the number of callers skipped by caller annotation (as enabled by the AddCaller option).

func AddStacktrace

func AddStacktrace(lvl Level) Option

AddStacktrace configures the Logger to record a stack trace for all messages at or above a given level.

func ErrorOutput

func ErrorOutput(w io.Writer) Option

ErrorOutput sets the destination for errors generated by the Logger. Note that this option only affects internal errors; for sample code that sends error-level logs to a different location from info- and debug-level logs, see the package-level AdvancedConfiguration example.

func Fields

func Fields(fs map[string]interface{}) Option

Fields adds fields to the Logger.

func SetProjectName

func SetProjectName(pname string) Option

func WithEncoder

func WithEncoder(encoder Encoder) Option

func WithEncoderCfg

func WithEncoderCfg(cfg EncoderConfig) Option

func WithLevelEnabler

func WithLevelEnabler(lvl Level) Option

LevelEnabler decides whether a given logging level is enabled when logging a message.

func WithOnFatal

func WithOnFatal(onFatal any) Option

func WithWriter

func WithWriter(writer io.Writer) Option

type Options

type Options struct {
	Writer       io.Writer
	ErrWriter    io.Writer
	Fields       map[string]interface{}
	LevelEnabler Level
	AddStack     Level
	AddCaller    bool
	CallerSkip   int
	EncoderCfg   EncoderConfig
	Encoder      Encoder
	OnFatal      any
}

type TimeEncoder

type TimeEncoder int

A TimeEncoder serializes a time.Time to a primitive type.

const (
	RFC3339TimeEncoder TimeEncoder = iota
	RFC3339MilliTimeEncoder
	RFC3339NanoTimeEncoder
)

type ZapOption

type ZapOption interface {
	// contains filtered or unexported methods
}

func WithZapEncoder

func WithZapEncoder(encoder zapcore.Encoder) ZapOption

func WithZapErrWriter

func WithZapErrWriter(w io.Writer) ZapOption

func WithZapFields

func WithZapFields(fields []zap.Field) ZapOption

func WithZapLevelEnabler

func WithZapLevelEnabler(lv Level) ZapOption

func WithZapOnFatal

func WithZapOnFatal(onFatal zapcore.CheckWriteHook) ZapOption

func WithZapOptions

func WithZapOptions(zopts []zap.Option) ZapOption

func WithZapWriter

func WithZapWriter(w io.Writer) ZapOption

Directories

Path Synopsis
writer
rotate/file-rotatelogs
package rotatelogs is a port of File-RotateLogs from Perl (https://metacpan.org/release/File-RotateLogs), and it allows you to automatically rotate output files when you write to them according to the filename pattern that you can specify.
package rotatelogs is a port of File-RotateLogs from Perl (https://metacpan.org/release/File-RotateLogs), and it allows you to automatically rotate output files when you write to them according to the filename pattern that you can specify.

Jump to

Keyboard shortcuts

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