import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" )
func zapExample() { logger, err := zap.NewProduction() if err != nil { panic(err) } defer logger.Sync() logger.Info("这是一条信息日志", zap.String("key", "value"), zap.Int("number", 42), ) devLogger, _ := zap.NewDevelopment() defer devLogger.Sync() devLogger.Debug("调试信息", zap.String("module", "auth"), zap.Duration("latency", 150*time.Millisecond), ) config := zap.Config{ Level: zap.NewAtomicLevelAt(zap.InfoLevel), Development: false, Sampling: &zap.SamplingConfig{ Initial: 100, Thereafter: 100, }, Encoding: "json", EncoderConfig: zapcore.EncoderConfig{ TimeKey: "ts", LevelKey: "level", NameKey: "logger", CallerKey: "caller", FunctionKey: zapcore.OmitKey, MessageKey: "msg", StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.LowercaseLevelEncoder, EncodeTime: zapcore.EpochTimeEncoder, EncodeDuration: zapcore.SecondsDurationEncoder, EncodeCaller: zapcore.ShortCallerEncoder, }, OutputPaths: []string{"stdout", "/tmp/zap.log"}, ErrorOutputPaths: []string{"stderr"}, } customLogger, _ := config.Build() defer customLogger.Sync() customLogger.Warn("自定义配置警告", zap.String("service", "api"), zap.Int("port", 8080), ) sugar := customLogger.Sugar() sugar.Infow("糖语法日志", "url", "https://example.com", "attempt", 3, "backoff", time.Second, ) }
|