企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> zap是uber开源的Go高性能日志库 [TOC] ## 安装 ~~~ go get -u go.uber.org/zap ~~~ ## 封装函数 (/utils/zap_logger/logger.go) ~~~ package zap_logger import ( "fmt" "go.uber.org/zap" "go.uber.org/zap/zapcore" "os" ) var Logger *zap.Logger var SugarLogger *zap.SugaredLogger func init() { fmt.Println("------------init logger----------") var err error var rootPath string // 构造EncoderConfig encoderConfig := zapcore.EncoderConfig{ TimeKey: "timestamp", LevelKey: "severity", NameKey: "logger", CallerKey: "caller", MessageKey: "message", StacktraceKey: "stacktrace", LineEnding: "\n", EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: zapcore.ISO8601TimeEncoder, EncodeDuration: zapcore.SecondsDurationEncoder, EncodeCaller: zapcore.FullCallerEncoder, } if rootPath, err = os.Getwd(); err != nil { panic(err) } // 构造 Config config := zap.Config{ Level: zap.NewAtomicLevelAt(zapcore.DebugLevel), Development: true, Encoding: "json", EncoderConfig: encoderConfig, InitialFields: map[string]interface{}{"MyName": "kainhuck"}, OutputPaths: []string{rootPath + "/runtime/zap2.log"}, ErrorOutputPaths: []string{rootPath + "/runtime/zap2.log"}, } // 可以构造Logger了 Logger, err = config.Build() if err != nil { panic(err) } // 然后是SugarLogger SugarLogger = Logger.Sugar() fmt.Println("------------init logger----end------") } func Error(args ...interface{}) { SugarLogger.Error(args) } func Debug(args ...interface{}) { SugarLogger.Debug(args) } func Info(args ...interface{}) { SugarLogger.Info(args) } func Warn(args ...interface{}) { SugarLogger.Warn(args) } ~~~ ## 测试调用函数 ~~~ //zap_logger.Debug("this is debug info") zap_logger.Error("this is debug info") ~~~