log4j2,yml - ThreadContext value is empty



我使用的是spring-bot-starter-log4j2:2.1.2.RELASE和log4j2.yml文件。在我的应用程序代码上

private static final Logger logger = LogManager.getLogger(LoggingAspect.class);
...
ThreadContext.put("hostname", InetAddress.getLocalHost().getHostName());
...
logger.error("message");

和log4j2.yml文件,

Appenders:
RollingRandomAccessFile:
- name: Alerts
filename: ...
filePattern: ...
PatternLayout:
Pattern: "%d{yyyy-MM-dd HH:mm:ss} %-5p %X{hostname}:%m%n"

在日志文件中,主机名丢失,而时间戳和消息按预期显示。我试过${ctx:hostname}、$${ctx:hostname},但到目前为止都不起作用

请引导我。

谢谢!

%X{hostname}只有在ThreadContext中添加主机名值时才有效。但你不需要这么做。Log4J会自动为您填充一个主机名变量。因此,只需在模式中指定${hostName}即可。

最新更新