说明如何在日志中间件中实现“动态采样”(1/1000 错误全量,其余 1%),并支持热配置

解读

国内一线/二线互联网公司在落地 Go-kit 时,日志量动辄 TB 级,全量落盘或全量上报会压垮 Loki/ELK/自研日志平台。面试官想验证三点:

  1. 对 Go-kit 洋葱式中间件模型的理解是否到位,能否在不改业务代码的前提下把“采样逻辑”插进去;
  2. 是否能把“错误全量/成功采样”这种分级策略做进同一段代码,而不是写两套 if-else;
  3. 是否具备“热更新”意识:配置变更不能重启 Pod,且要保证并发安全、性能损耗极低。

因此,答题必须给出:①中间件代码骨架;②采样算法;③配置热加载机制;④线程安全与性能考量;⑤可观测性(自监控采样率命中率)。

知识点

  1. Go-kit 中间件签名:func(logger log.Logger) endpoint.Middleware
  2. 概率采样与确定性采样:错误码>0 走确定性 100%,成功码走概率 1%,需用原子计数器避免锁竞争
  3. 热配置通道:使用 github.com/fsnotify/fsnotify 监听 ConfigMap 变更(K8s 场景),或接入 Nacos/Apollo;配置结构体采用 atomic.Value 无锁替换
  4. 零内存分配:采样决策在日志中间件最前端完成,避免构造昂贵 log.Context;决策失败直接 return next(ctx, request)
  5. 自监控:暴露 Prometheus 指标 sampled_logs_total{code, decision},方便 SRE 校验采样比是否符合预期

答案

// 1. 配置模型
type LogSampleConfig struct {
    ErrorSampleRate  int    `json:"error_sample_rate"`  // 错误全量=1 表示 1/1
    SuccessSampleRate int   `json:"success_sample_rate"`// 成功采样=100 表示 1/100
}

// 2. 全局热配置容器
var (
    cfg atomic.Value // 里面存 *LogSampleConfig
    hitCounter uint64 // 原子计数器,用于成功采样
)

// 3. 监听 ConfigMap(K8s 场景)
func watchConfig(path string) {
    w, _ := fsnotify.NewWatcher()
    w.Add(path)
    for e := range w.Events {
        if e.Op&fsnotify.Write == fsnotify.Write {
            data, _ := os.ReadFile(path)
            var c LogSampleConfig
            if json.Unmarshal(data, &c) == nil {
                cfg.Store(&c)
            }
        }
    }
}

// 4. 采样决策函数,零分配
func shouldLog(err error) bool {
    c := cfg.Load().(*LogSampleConfig)
    if err != nil {
        return rand.Intn(c.ErrorSampleRate) == 0 // 错误全量时 c.ErrorSampleRate=1
    }
    // 成功采样:原子递增后取模
    return uint64(rand.Intn(c.SuccessSampleRate)) == 0
}

// 5. Go-kit 日志中间件
func LogMiddleware(logger log.Logger) endpoint.Middleware {
    return func(next endpoint.Endpoint) endpoint.Endpoint {
        return func(ctx context.Context, request interface{}) (response interface{}, err error) {
            // 前置决策
            if !shouldLog(err) {
                return next(ctx, request)
            }
            // 需要记录:构造日志上下文
            begin := time.Now()
            response, err = next(ctx, request)
            logger.Log(
                "method", ctx.Value("method"),
                "duration", time.Since(begin),
                "err", err,
            )
            return
        }
    }
}

落地步骤:

  1. 把配置写进 K8s ConfigMap,挂载到 Pod 的 /etc/log-sampler/config.json;
  2. 主函数启动 goroutine go watchConfig("/etc/log-sampler/config.json");
  3. 在 main 里把 LogMiddleware(logger) 塞进服务端 r := mux.NewRouter(); r.Use(LogMiddleware);
  4. 用 Prometheus 记录 sampled_logs_total,Grafana 大盘对比“实际日志条数 / 采样条数”,验证 1/1000 错误全量、1% 成功采样是否达标。

拓展思考

  1. 多级采样:在错误里再细分“5xx 全量、4xx 1/10”,可把 shouldLog 升级为策略链,支持按业务自定义规则;
  2. 动态权重:结合 QPS 自适应,当流量突增 10 倍时自动把成功采样率从 1% 降到 0.1%,防止日志平台被打爆;
  3. 链路染色:在 Header 中携带 X-Log-Full=1 时强制旁路采样,方便压测或问题追踪;
  4. 与 OpenTelemetry 集成:把采样决策结果写回 Span Attribute,实现“Trace 与日志采样对齐”,避免链路完整但日志缺失的尴尬;
  5. 配置灰度:利用 Apollo 的灰度发布能力,先让 10% Pod 加载新采样率,监控指标无异常再全量推送,降低误杀风险。