将诊断结果输出到 Grafana Loki

解读

在国内微服务与云原生落地场景中,可观测性已成为面试必考项。Groovy 常被用作 Gradle 插件、Spock 测试或 Jenkins 共享库的“胶水”语言,因此面试官更关注“如何用 Groovy 把运行时诊断数据低成本推送到 Loki”,而非 Java 那套重型方案。考点集中在:

  1. 是否理解 Loki 仅接受 流式日志(stream+log)模型;
  2. 能否用 Groovy 的动态特性+闭包快速组装标签并批量推送;
  3. 是否知道**国内云厂商内网地址、鉴权方式(阿里云 SLS 代理、华为云 LTS 转发)**与开源 Loki 的差异;
  4. 是否具备背压、重试、批量压缩等生产意识,避免直接把诊断日志打爆网关。

知识点

  1. Loki 数据模型:labels + nanosecond-timestamp + message;labels 必须稳定,否则产生“流爆炸”。
  2. Groovy 侧核心库:HttpBuilder-NG(同步/异步均支持,兼容 Java8 到 Java17)、Grape 即时依赖,无需打包。
  3. 批量推送端点:/loki/api/v1/push,Content-Type: application/json; charset=utf-8,gzip 压缩必须开启,国内公网上传 4 MB 以上会被 CDN 直接 reset。
  4. 鉴权:Bearer Token(开源 Loki)、阿里云 AK/SK 签名(若走 SLS 代理)、华为云 IAM Token(若走 LTS 转发);Groovy 闭包可封装统一签名算法。
  5. 诊断数据格式:建议统一为 JSON Lines,字段 level、thread、logger、stackHash、traceId;通过 JsonOutput.toJson() 序列化,避免 toString() 中文乱码。
  6. 性能陷阱:
    • 单批次≤1000 条、≤1 MB;
    • 采用 LinkedBlockingQueue + ScheduledThreadPoolExecutor 做异步刷盘,防止业务线程阻塞;
    • 失败重试采用指数退避 + 最大 3 次,避免 Loki 出现“too many unhealthy ingester”时把服务拖死。
  7. 监控自身:推送失败次数、队列堆积量通过 Micrometer + Groovy 注解暴露到 /actuator/metrics,供 Prometheus 二次抓取,形成闭环。

答案

以下示例基于开源 Loki,Groovy 3+ 验证通过,可直接在 Gradle 构建脚本或 Spock 测试的 setup() 中引用。核心思路:异步攒批 → 压缩 → 带重试推送 → 异常安全。

@Grab('io.github.http-builder-ng:http-builder-ng-core:1.0.4')
@Grab('org.slf4j:slf4j-simple:1.7.36')
import groovy.json.JsonOutput
import groovy.transform.CompileStatic
import java.util.concurrent.*
import java.util.zip.GZIPOutputStream

@CompileStatic
class LokiDiagnosticReporter {
    private final BlockingQueue<Map> queue = new LinkedBlockingQueue<>(10000)
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor()
    private final String pushUrl
    private final String bearerToken
    private final int batchSize
    private final long flushMillis

    LokiDiagnosticReporter(String pushUrl, String bearerToken,
                           int batchSize = 500, long flushMillis = 1000) {
        this.pushUrl = pushUrl
        this.bearerToken = bearerToken
        this.batchSize = batchSize
        this.flushMillis = flushMillis
        scheduler.scheduleWithFixedDelay(this.&flush, flushMillis, flushMillis, TimeUnit.MILLISECONDS)
    }

    void log(String level, String logger, String message, Map extra = [:]) {
        Map rec = [
            level  : level,
            logger : logger,
            message: message,
            ts     : System.currentTimeMillis() * 1_000_000, // nano
            extra  : extra
        ]
        if (!queue.offer(rec)) {
            System.err.println("Loki queue full, drop diagnostic log")
        }
    }

    private void flush() {
        if (queue.isEmpty()) return
        List<Map> batch = []
        queue.drainTo(batch, batchSize)
        if (batch.isEmpty()) return
        // 统一标签:job=diagnostic, pod=hostname
        String hostname = InetAddress.localHost.hostName
        Map labels = [job: 'diagnostic', pod: hostname]
        // 构造 Loki 格式
        List streams = [[
            stream: labels,
            values: batch.collect { [String.valueOf(it.ts), JsonOutput.toJson(it)] }
        ]]
        byte[] body = JsonOutput.toJson(streams).bytes
        byte[] gzipBody = body.encodeGzip()
        retry(times: 3, sleep: 300) {
            new groovyx.net.http.HttpBuilder.configure {
                request.uri = pushUrl
                request.contentType = 'application/json'
                request.headers['Authorization'] = "Bearer ${bearerToken}"
                request.headers['Content-Encoding'] = 'gzip'
                request.body = gzipBody
                request.post {
                    response.success { fs ->
                        if (fs.statusCode >= 300) throw new IOException("Loki ${fs.statusCode}")
                    }
                }
            }
        }
    }

    private static void retry(Map cfg, Closure c) {
        int times = cfg.times as int
        long sleep = cfg.sleep as long
        Throwable last
        for (int i in 1..times) {
            try {
                c.call(); return
            } catch (Throwable t) {
                last = t
                if (i < times) Thread.sleep(sleep * (2 << i))
            }
        }
        System.err.println("Loki push failed after ${times} times: ${last.message}")
    }

    void shutdown() {
        scheduler.shutdown()
        flush() // 最后兜底
    }
}

// ===== 使用示例 =====
def reporter = new LokiDiagnosticReporter(
    'http://loki-gateway.mycluster.local/loki/api/v1/push',
    System.getenv('LOKI_TOKEN')
)

// 在 Gradle 构建脚本里捕捉任务失败
gradle.taskGraph.afterTask { task ->
    if (task.state.failure) {
        reporter.log('ERROR', 'gradle', "Task ${task.path} failed",
                     [exception: task.state.failure.message])
    }
}

// 在 Spock 测试里记录慢用例
def setup() {
    specificationContext.with {
        if (iteration.estimatedDurationMillis > 5000) {
            reporter.log('WARN', 'spock', "Slow test: ${iteration.displayName}",
                         [duration: iteration.estimatedDurationMillis])
        }
    }
}

要点回顾:

  • 采用 Grape 自动抓取依赖,无需企业私服即可落地;
  • 队列 + 定时器实现背压与批量,避免逐条 HTTP 打爆 Loki;
  • gzip 压缩后体积 <10%,内网传输 1 MB 以内符合阿里云 SLS 免费额度;
  • 重试策略指数退避,防止因 ingester 瞬时不可用导致诊断数据丢失;
  • 统一标签 job=diagnostic, pod=hostname,防止流爆炸;
  • 最后 shutdown() 强制刷盘,确保 Jenkins Pipeline 或 Gradle Daemon 退出前数据不丢。

拓展思考

  1. 若公司使用阿里云 SLS 代理 Loki,需把签名算法(RFC 7616)封装到 Groovy 闭包里,并在 header 加入 x-sls-apiversion: 0.6.0;此时推送地址变为 https://{project}.{region}.sls.aliyuncs.com/loki/api/v1/push,切勿把 Token 打到日志。
  2. 当诊断量暴涨(>5k 条/秒)时,可把上述 reporter 改造成 gRPC 模式,利用 Loki 的 Push API v2(需启用 distributor.ingestion-rate-limit),Groovy 通过 grpc-okhttp 动态 stub 即可,延迟从 200 ms 降到 30 ms。
  3. 为了审计合规,可在 Groovy 侧先写本地 WAL(Write-Ahead-Log) 文件,格式为 NDJSON,每 64 MB 滚动;后台协程异步压缩上传至 OSS/S3,再批量导入 Loki,实现“断网续传”,满足金融级可观测性要求。