在<<微服务基于请求的日志跟踪>>上设计了基于请求的微服务日志处理方法, 但是发现在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到日志文件了.
网友评论