如何在Ballerina微服务中使用Correlation ID进行日志记录?
Ballerina HTTP服务日志添加Correlation ID的实现方案
要给Ballerina HTTP服务的每条日志加上Correlation ID,核心思路是在请求入口处生成/获取唯一标识,将其绑定到请求上下文,然后在日志输出时自动附加该标识。以下是具体的落地方案:
实现步骤
1. 引入拦截器处理Correlation ID
利用Ballerina HTTP的拦截器机制,在请求进入时完成Correlation ID的获取或生成,并存入请求上下文:
import ballerina/http; import ballerina/log; import ballerina/uuid; type Album readonly & record {| string title; string artist; |}; table<Album> key(title) albums = table [ {title: "Blue Train", artist: "John Coltrane"}, {title: "Jeru", artist: "Gerry Mulligan"} ]; // 定义Correlation ID拦截器 type CorrelationInterceptor record {| *http:Interceptor; |}; // 拦截请求,处理Correlation ID function handleRequest(http:RequestContext ctx, http:Request req) returns error? { // 优先从请求头X-Correlation-ID获取,无则生成UUID string correlationId = req.getHeader("X-Correlation-ID") ?: uuid:createType1AsString(); // 将ID存入请求上下文 ctx.set("CORRELATION_ID", correlationId); return ctx.proceed(); } // 实例化拦截器 final CorrelationInterceptor correlationInterceptor = new (handleRequest = handleRequest);
2. 封装带Correlation ID的日志函数
写一个自定义日志工具函数,自动从上下文取出Correlation ID并附加到日志内容:
// 自定义日志输出,自动携带Correlation ID function logWithCorrelationId(http:RequestContext ctx, string message) { string? correlationId = ctx.get("CORRELATION_ID"); log:printInfo(string `[Correlation-ID: ${correlationId ?: "UNKNOWN"}] ${message}`); }
3. 修改服务绑定拦截器并使用自定义日志
在服务监听配置中添加拦截器,资源函数中通过上下文调用自定义日志:
service / on new http:Listener(9090, interceptors = [correlationInterceptor]) { resource function get albums(http:RequestContext ctx) returns Album[] { logWithCorrelationId(ctx, "开始处理专辑列表查询请求"); Album[] albumList = albums.toArray(); logWithCorrelationId(ctx, "专辑列表查询完成,共返回${albumList.length()}条数据"); return albumList; } }
额外说明
- 如果需要在跨模块的函数(如数据查询、外部调用)中传递Correlation ID,可将
http:RequestContext作为参数传入,或使用Ballerina的context:Context进行全局上下文传递。 - 若要全局统一日志格式,也可通过修改Ballerina的日志配置文件,但拦截器方式更灵活,能针对请求链路做细粒度控制。
内容的提问来源于stack exchange,提问作者Nipuna Madhushan
相关产品推荐
相关产品推荐

