// Copyright 2019 github.com. All rights reserved. // Use of this source code is governed by github.com. package logger import ( "context" "fmt" "git.getensh.com/common/gopkgs/id" jsoniter "github.com/json-iterator/go" "go.uber.org/zap" ) // 替换标准库 encoding/json var json = jsoniter.ConfigCompatibleWithStandardLibrary var l *zap.Logger // New 新建日志器 func New(env, level, filename string, maxSize, maxBackups, maxAge int, stacktrace, global bool) *zap.Logger { encoding := "json" development := true if env == "prod" { development = false } js := fmt.Sprintf(`{ "level": "%s", "encoding": "%s", "outputPath": "%s" }`, level, encoding, filename) zcfg := zapConfig{} if err := json.Unmarshal([]byte(js), &zcfg); err != nil { panic(err) } zcfg.Development = development zcfg.DisableStacktrace = !stacktrace logger := zcfg.New(maxSize, maxBackups, maxAge) if global { l = logger } return logger } // Error log func Error(msg string, fields ...zap.Field) { if l != nil { l.Error(msg, fields...) } } // Info log func Info(msg string, fields ...zap.Field) { if l != nil { l.Info(msg, fields...) } } // Debug log func Debug(msg string, fields ...zap.Field) { if l != nil { l.Debug(msg, fields...) } } // ErrorWithCtx log func ErrorWithCtx(ctx context.Context, msg string, fields ...zap.Field) { if l != nil { fields = append(fields, zap.String("requestId", id.GetRequestId(ctx))) l.Error(msg, fields...) } } // InfoWithCtx log func InfoWithCtx(ctx context.Context, msg string, fields ...zap.Field) { if l != nil { fields = append(fields, zap.String("requestId", id.GetRequestId(ctx))) l.Info(msg, fields...) } } // DebugWithCtx log func DebugWithCtx(ctx context.Context, msg string, fields ...zap.Field) { if l != nil { fields = append(fields, zap.String("requestId", id.GetRequestId(ctx))) l.Debug(msg, fields...) } }