美文网首页Golang相关
go日志框架zap配置示例

go日志框架zap配置示例

作者: AlberLiu | 来源:发表于2018-11-15 18:26 被阅读3次
    package log
    
    import (
        "testing"
        "time"
    
        "os"
    
        "go.uber.org/zap"
        "go.uber.org/zap/zapcore"
        "gopkg.in/natefinch/lumberjack.v2"
    )
    
    func NewEncoderConfig() zapcore.EncoderConfig {
        return zapcore.EncoderConfig{
            // Keys can be anything except the empty string.
            TimeKey:        "T",
            LevelKey:       "L",
            NameKey:        "N",
            CallerKey:      "C",
            MessageKey:     "M",
            StacktraceKey:  "S",
            LineEnding:     zapcore.DefaultLineEnding,
            EncodeLevel:    zapcore.CapitalLevelEncoder,
            EncodeTime:     TimeEncoder,
            EncodeDuration: zapcore.StringDurationEncoder,
            EncodeCaller:   zapcore.ShortCallerEncoder,
        }
    }
    
    func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
        enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
    }
    
    func TestLogrotate(t *testing.T) {
        w := zapcore.AddSync(&lumberjack.Logger{
            Filename:   "foo.log",
            MaxSize:    500, // megabytes
            MaxBackups: 3,
            MaxAge:     28, // days
        })
        core := zapcore.NewCore(
            zapcore.NewConsoleEncoder(NewEncoderConfig()),
            zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout),
                w),
            zap.DebugLevel,
        )
        logger := zap.New(core, zap.AddCaller())
        logger.Info("info")
    }
    
    

    打印结果:

    2018-11-15 18:23:07.985 INFO    log/zap_test.go:54  info
    

    相关文章

      网友评论

        本文标题:go日志框架zap配置示例

        本文链接:https://www.haomeiwen.com/subject/ajqufqtx.html