go-zap默认配置下日志缺失问题,程序执行正常而打印日志数量不符合预期

现象:

程序执行正常而打印日志数量不符合预期

 

原因:

默认配置下,日志会进行取样。

取样规则是,对于msg相同的日志,前100打印输出,之后每隔100条输出一条

Sampling: &SamplingConfig{
Initial: 100,
Thereafter: 100,
}
 

解决方案:去掉Sampling配置

config.Sampling = nil

 

默认配置信息:

复制代码
// NewProductionConfig is a reasonable production logging configuration.
// Logging is enabled at InfoLevel and above.
//
// It uses a JSON encoder, writes to standard error, and enables sampling.
// Stacktraces are automatically included on logs of ErrorLevel and above.
func NewProductionConfig() Config {
    return Config{
        Level:       NewAtomicLevelAt(InfoLevel),
        Development: false,
        Sampling: &SamplingConfig{
            Initial:    100,
            Thereafter: 100,
        },
        Encoding:         "json",
        EncoderConfig:    NewProductionEncoderConfig(),
        OutputPaths:      []string{"stderr"},
        ErrorOutputPaths: []string{"stderr"},
    }
}
View Code
复制代码

 

测试代码:

复制代码
package main

import (
    "go.uber.org/zap"
)

func main() {

    // 默认配置
    config := zap.NewProductionConfig()
    logger, _ := config.Build()

    for i := 0; i < 1000; i++ {
        logger.Info("test log ------", zap.Any("num", i))
    }

    // 关闭取样
    config.Sampling = nil
    logger1, _ := config.Build()
    for i := 0; i < 200; i++ {
        logger1.Info("test log +++++++", zap.Any("num", i))
    }

}
View Code
复制代码

 

posted @   雪梨大佬  阅读(161)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示