log

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2023 License: MIT Imports: 12 Imported by: 3

README

emorydu/log

emorydu/log 是一个生产可用的日志包,基于 zap 包封装。除了实现 Go 日志包的基本功能外,还实现了很多高级功能,emorydu/log具有如下特性:

  • 支持日志级别:DebugInfoWarnErrorPanicFatal
  • 支持自定义配置。
  • 支持文件名和行号。
  • 支持输出掉标准输出和文件,可以同时输出到多个地方。
  • 支持 JSONText 两种日志格式。
  • 支持颜色输出。
  • 兼容标准的 log 包。
  • 高性能。
  • 支持结构化日志记录。
  • 兼容标准库 log 包和 glog
  • 支持Context(业务定制)
  • 支持Cutter (日志拆分)

使用方法

一个简单的示例

创建一个 example2.go 文件,内容如下:

package main

import (
    "github.com/emorydu/iam/pkg/log"
)

func main() {
    defer log.Flush()

    // Debug、Info(with field)、Warnf、Errorw使用
    log.Debug("This is a debug message")
    log.Info("This is a info message", log.Int32("int_key", 10))
    log.Warnf("This is a formatted %s message", "warn")
}

执行代码:

$ go run example2.go 
2020-12-05 07:56:37.154	info	example/example2.go:12	This is a info message	{"int_key": 10}
2020-12-05 07:56:37.154	warn	example/example2.go:13	This is a formatted warn message

上述代码使用 marmotedu/log 包默认的全局 logger,分别在 DebugInfoWarn 级别打印了一条日志。

初始化日志包

可以使用 Init 来初始化一个日志包,如下:

// logger配置    
opts := &log.Options{
    Level:            "debug",
    Format:           "console",
    EnableColor:      true,
    EnableCaller:     true,
    OutputPaths:      []string{"test.log", "stdout"},
    ErrorOutputPaths: []string{"error.log"},
}
// 初始化全局logger    
log.Init(opts)

Format 支持 consolejson 2 种格式:

  • console:输出为 text 格式。例如:2020-12-05 08:12:02.324 DEBUG example/example.go:43 This is a debug message
  • json:输出为 json 格式,例如:{"level":"debug","time":"2020-12-05 08:12:54.113","caller":"example/example.go:43","msg":"This is a debug message"}

OutputPaths,可以设置日志输出:

  • stdout:输出到标准输出。
  • stderr:输出到标准错误输出。
  • /var/log/test.log:输出到文件。

支持同时输出到多个输出。

EnableColor 为 true 开启颜色输出,为 false 关闭颜色输出。

结构化日志输出

emorydu/log 也支持结构化日志打印,例如:

log.Info("This is a info message", log.Int32("int_key", 10))
log.Infow("Message printed with Errorw", "X-Request-ID", "fbf54504-64da-4088-9b86-67824a7fb508") 

对应的输出结果为:

2020-12-05 08:16:18.749	INFO	example/example.go:44	This is a info message	{"int_key": 10}
2020-12-05 08:16:18.749	ERROR	example/example.go:46	Message printed with Errorw	{"X-Request-ID": "fbf54504-64da-4088-9b86-67824a7fb508"}

log.Info 这类函数需要指定具体的类型,以最大化的 提高日志的性能。log.Infow 这类函数,不用指定具体的类型,底层使用了反射,性能会差些。建议用在低频调用的函数中。

支持V level

创建 v_level.go,内容如下:

package main

import (
    "github.com/emorydu/iam/pkg/log"
)

func main() {
    defer log.Flush()

    log.V(0).Info("This is a V level message")
    log.V(0).Infow("This is a V level message with fields", "X-Request-ID", "7a7b9f24-4cae-4b2a-9464-69088b45b904")
}

执行如上代码:

$ go run v_level.go 
2020-12-05 08:20:37.763	info	example/v_level.go:10	This is a V level message
2020-12-05 08:20:37.763	info	example/v_level.go:11	This is a V level message with fields	{"X-Request-ID": "7a7b9f24-4cae-4b2a-9464-69088b45b904"}

支持日志拆分

创建 cutter.go,内容如下:

func main() {
    opts := &log.Options{
        OutputPaths:      []string{"cutter.log"},
        ErrorOutputPaths: []string{"error.log"},
        Level:            "debug",
        Format:           "console",
        Name:             "test",
    }
    opts.Cutter = &lumberjack.Logger{
        Filename:   opts.OutputPaths[0],
        MaxSize:    1, // 单位M
        MaxAge:     3,
        MaxBackups: 30,
        Compress:   false, // 是否压缩
    }
    l := log.New(opts)
    for i := 0; i < 10000; i++ {
        l.Info("Info message")
        l.Debug("Debug message")
        l.Error("Error message")
    }
}

执行如上代码

go run cutter.go
# 会产生按照大小分割的日志文件

完整的示例

一个完整的示例请参考example.go

Documentation

Index

Constants

View Source
const (
	KeyRequestID   string = "requestID"
	KeyUsername    string = "username"
	KeyWatcherName string = "watcher"
)

Variables

View Source
var (
	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel = zapcore.DebugLevel
	// InfoLevel is the default logging priority.
	InfoLevel = zapcore.InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual
	// human review.
	WarnLevel = zapcore.WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-level logs.
	ErrorLevel = zapcore.ErrorLevel
	// PanicLevel logs a message, then panics.
	PanicLevel = zapcore.PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel = zapcore.FatalLevel
)
View Source
var (
	Any         = zap.Any
	Array       = zap.Array
	Object      = zap.Object
	Binary      = zap.Binary
	Bool        = zap.Bool
	Bools       = zap.Bools
	ByteString  = zap.ByteString
	ByteStrings = zap.ByteStrings
	Complex64   = zap.Complex64
	Complex64s  = zap.Complex64s
	Complex128  = zap.Complex128
	Complex128s = zap.Complex128s
	Duration    = zap.Duration
	Durations   = zap.Durations
	Err         = zap.Error
	Errors      = zap.Errors
	Float32     = zap.Float32
	Float32s    = zap.Float32s
	Float64     = zap.Float64
	Float64s    = zap.Float64s
	Int         = zap.Int
	Ints        = zap.Ints
	Int8        = zap.Int8
	Int8s       = zap.Int8s
	Int16       = zap.Int16
	Int16s      = zap.Int16s
	Int32       = zap.Int32
	Int32s      = zap.Int32s
	Int64       = zap.Int64
	Int64s      = zap.Int64s
	Namespace   = zap.Namespace
	Reflect     = zap.Reflect
	Stack       = zap.Stack
	String      = zap.String
	Stringer    = zap.Stringer
	Strings     = zap.Strings
	Time        = zap.Time
	Times       = zap.Times
	Uint        = zap.Uint
	Uints       = zap.Uints
	Uint8       = zap.Uint8
	Uint8s      = zap.Uint8s
	Uint16      = zap.Uint16
	Uint16s     = zap.Uint16s
	Uint32      = zap.Uint32
	Uint32s     = zap.Uint32s
	Uint64      = zap.Uint64
	Uint64s     = zap.Uint64s
	Uintptr     = zap.Uintptr
	Uintptrs    = zap.Uintptrs
)

Alias for zap type functions.

Functions

func CheckIntLevel

func CheckIntLevel(level int32) bool

CheckIntLevel used for other log wrapper such as klog which return if logging a message at the specified level is enabled.

func Debug

func Debug(msg string, fields ...Field)

Debug method output debug level log.

func Debugf

func Debugf(format string, v ...interface{})

Debugf method output debug level log.

func Debugw

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

Debugw method output debug level log.

func Error

func Error(msg string, fields ...Field)

Error method output error level log.

func Errorf

func Errorf(format string, v ...interface{})

Errorf method output error level log.

func Errorw

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

Errorw method output error level log.

func Fatal

func Fatal(msg string, fields ...Field)

Fatal method output fatal level log.

func Fatalf

func Fatalf(format string, v ...interface{})

Fatalf method output fatal level log.

func Fatalw

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

Fatalw method output Fatalw level log.

func Flush

func Flush()

Flush calls the underlying Core's Sync method, flushing any buffered log entries. Applications should take care to call Sync before exiting.

func Info

func Info(msg string, fields ...Field)

Info method output info level log.

func Infof

func Infof(format string, v ...interface{})

Infof method output info level log.

func Infow

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

Infow method output info level log.

func Init

func Init(opts *Options)

Init initializes logger with specified options.

func L

func L(ctx context.Context) *zapLogger

L method output with specified context value.

func New

func New(opts *Options) *zapLogger

New create logger by opts which can custmoized by command arguments.

func Panic

func Panic(msg string, fields ...Field)

Panic method output panic level log and shutdown application.

func Panicf

func Panicf(format string, v ...interface{})

Panicf method output panic level log and shutdown application.

func Panicw

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

Panicw method output panic level log.

func StdErrLogger

func StdErrLogger() *log.Logger

StdErrLogger returns logger of standard library which writes to supplied zap logger at error level.

func StdInfoLogger

func StdInfoLogger() *log.Logger

StdInfoLogger returns logger of standard library which writes to supplied zap logger at info level.

func SugaredLogger

func SugaredLogger() *zap.SugaredLogger

SugaredLogger returns global sugared logger.

func Warn

func Warn(msg string, fields ...Field)

Warn method output warning level log.

func Warnf

func Warnf(format string, v ...interface{})

Warnf method output warning level log.

func Warnw

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

Warnw method output warning level log.

func WithContext

func WithContext(ctx context.Context) context.Context

WithContext returns a copy of context in which the log value is set.

func ZapLogger

func ZapLogger() *zap.Logger

ZapLogger used for other log wrapper such as klog.

Types

type Field

type Field = zapcore.Field

Field is an alias for the field structure in the underlying log frame.

type InfoLogger

type InfoLogger interface {
	// Info logs a non-error message with the given key/value pairs as context.
	//
	// The msg argument should be used to add some constant description to
	// the log line.  The key/value pairs can then be used to add additional
	// variable information.  The key/value pairs should alternate string
	// keys and arbitrary values.
	Info(msg string, fields ...Field)
	Infof(format string, v ...interface{})
	Infow(msg string, keysAndValues ...interface{})

	// Enabled tests whether this InfoLogger is enabled.  For example,
	// commandline flags might be used to set the logging verbosity and disable
	// some info logs.
	Enabled() bool
}

InfoLogger represents the ability to log non-error messages, at a particular verbosity.

func V

func V(level Level) InfoLogger

V returns leveled InfoLogger.

type Level

type Level = zapcore.Level

Level is an alias for the level structure in the underlying log frame.

type Logger

type Logger interface {
	InfoLogger
	Debug(msg string, fields ...Field)
	Debugf(format string, v ...interface{})
	Debugw(msg string, keysAndValues ...interface{})
	Warn(msg string, fields ...Field)
	Warnf(format string, v ...interface{})
	Warnw(msg string, keysAndValues ...interface{})
	Error(msg string, fields ...Field)
	Errorf(format string, v ...interface{})
	Errorw(msg string, keysAndValues ...interface{})
	Panic(msg string, fields ...Field)
	Panicf(format string, v ...interface{})
	Panicw(msg string, keysAndValues ...interface{})
	Fatal(msg string, fields ...Field)
	Fatalf(format string, v ...interface{})
	Fatalw(msg string, keysAndValues ...interface{})

	// V returns an InfoLogger value for a specific verbosity level.  A higher
	// verbosity level means a log message is less important.  It's illegal to
	// pass a log level less than zero.
	V(level Level) InfoLogger
	Write(p []byte) (n int, err error)

	// WithValues adds some key-value pairs of context to a logger.
	// See Info for documentation on how key/value pairs work.
	WithValues(keysAndValues ...interface{}) Logger

	// WithName adds a new element to the logger's name.
	// Successive calls with WithName continue to append
	// suffixes to the logger's name. It's strongly recommended
	// that name segments contain only letters, digits, and hyphens
	// (see the package documentation for more information).
	WithName(name string) Logger

	// WithContext returns a copy of context in which the log value is set.
	WithContext(ctx context.Context) context.Context

	// Flush calls the underlying Core's Sync method, flushing any buffered
	// log entries. Applications should take care to call Sync before exiting.
	Flush()
}

Logger represents the ability to log message, both errors and not.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext returns the value of the log key on the ctx.

func NewLogger

func NewLogger(l *zap.Logger) Logger

NewLogger creates a new logr.Logger using the given Zap Logger to log.

func WithName

func WithName(s string) Logger

WithName adds a new path segment to the logger's name, Segments are joined by periods. By default, Loggers are unnamed.

func WithValues

func WithValues(keysAndValues ...interface{}) Logger

WithValues creates a child logger and adds Zap fields to it.

type Options

type Options struct {
	OutputPaths       []string           `json:"output-paths" mapstructure:"output-paths"`
	ErrorOutputPaths  []string           `json:"error-output-paths" mapstructure:"error-output-paths"`
	Level             string             `json:"level" mapstructure:"level"`
	Format            string             `json:"format" mapstructure:"format"`
	DisableCaller     bool               `json:"disable-caller" mapstructure:"disable-caller"`
	DisableStacktrace bool               `json:"disable-stacktrace" mapstructure:"disable-stacktrace"`
	EnableColor       bool               `json:"enable-color" mapstructure:"enable-color"`
	Development       bool               `json:"development" mapstructure:"development"`
	Name              string             `json:"name" mapstructure:"name"`
	Cutter            *lumberjack.Logger `json:"cutter" mapstructure:"cutter"`
}

Options defines configuration items related to log.

func NewOptions

func NewOptions() *Options

NewOptions creates an Options object with default parameters.

func (*Options) AddFlags

func (o *Options) AddFlags(fs *pflag.FlagSet)

AddFlags adds flags for log to the specified FlagSet object.

func (*Options) Build

func (o *Options) Build() error

Build constructs a global zap logger from the Config and Options.

func (*Options) String

func (o *Options) String() string

func (*Options) Validate

func (o *Options) Validate() []error

Validate the options fields.

Directories

Path Synopsis
Package klog init klog logger.
Package klog init klog logger.
Package logrus adds a hook to the logrus logger hooks.
Package logrus adds a hook to the logrus logger hooks.

Jump to

Keyboard shortcuts

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