微服务基于请求的异步日志跟踪

<<微服务基于请求的日志跟踪>>上设计了基于请求的微服务日志处理方法, 但是发现在log4j处于异步的情况下会失效, 原因是RequestId无法从原线程传输到打印日志的线程, 异步情况下(AsyncLoggerConfig), 日志先被enqueue到一个队列,然后若干线程去消费这个队列, 因为跨了线程,所以不能通过线程变量传递过去.
查看了相关代码, 发现log4j首先将message生成了LogEvent, 然后将LogEvent丢入队列, 而LogEvent提供了一个ContenxtData的Map来携带属性变量, 所以我们可以将RequestId放到这里面传递过去.

具体的代码是:

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.Property;
import org.apache.logging.log4j.core.impl.ContextDataFactory;
import org.apache.logging.log4j.core.impl.MutableLogEvent;
import org.apache.logging.log4j.core.impl.ReusableLogEventFactory;
import org.apache.logging.log4j.message.Message;
import org.apache.logging.log4j.util.StringMap;

import java.util.List;
public class RequestIdLogEventFactory extends ReusableLogEventFactory {
    @Override
    public LogEvent createEvent(String loggerName, Marker marker, String fqcn, Level level, Message message, List<Property> properties, Throwable t) {
        LogEvent event = super.createEvent(loggerName, marker, fqcn, level, message, properties, t);
        if (event instanceof MutableLogEvent) {
            StringMap contextData = ContextDataFactory.createContextData();
            contextData.putAll(event.getContextData());
            contextData.putValue("RequestId", LogRequestIdPlugin.getRequestId());
            ((MutableLogEvent) event).setContextData(contextData);
        }
        return event;
    }
    public static String getRequestId(LogEvent event) {
        return event.getContextData().getValue("RequestId");
    }
}

同时修改LogRequestIdPlugin:

    @Override
    public void format(LogEvent event, StringBuilder toAppendTo) {
       toAppendTo.append(RequestIdLogEventFactory.getRequestId(event));
    }

设置应用的启动参数, 指定logEvent工厂, 增加:

-DLog4jLogEventFactory=your_package.RequestIdLogEventFactory

这样即使在异步输出的时候,也能传递RequestId到日志文件了.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值