简体   繁体   English

如何在slf4j中使用Log4j2中的格式化消息

[英]How to use formatted message in Log4j2 with slf4j

Is it possible to format a log message with the syntax from String.format when Log4j2 is used behind slf4j? 在slf4j后面使用Log4j2时,是否可以使用String.format的语法格式化日志消息?

It seems the standard MessageFactory is ParameterizedMessageFactory which supports only {} . 看来标准的MessageFactoryParameterizedMessageFactory ,它仅支持{}

You cannot change the MessageFactory on a per Logger basis as you can with the Log4j API. 您不能像使用Log4j API那样在每个Logger的基础上更改MessageFactory。 However, you can change the default MessageFactory by setting log4j2.messageFactory to the MessageFactory class name you want to use. 但是,可以通过将log4j2.messageFactory设置为要使用的MessageFactory类名称来更改默认的MessageFactory。 You can either specify it as a system property or you can define the property in a file named log4j2.component.properties that can be found in the classpath. 您可以将其指定为系统属性,也可以在名为log4j2.component.properties的文件中定义该属性,该文件位于类路径中。

I would suggest you might want to consider using the FormattedMessageFactory as it supports String.format patterns, MessageFormat patterns and ParameterizedMessage patterns (not in the same message though). 我建议您可能要考虑使用FormattedMessageFactory,因为它支持String.format模式,MessageFormat模式和ParameterizedMessage模式(尽管不在同一条消息中)。

You can't do that without accessing the native logger, but that would be messy and not very useful, in the end. 您不能在不访问本机记录器的情况下执行此操作,但是最终这将很麻烦并且用处不大。 See this answer if you really want to do that. 如果您真的想这样做,请参阅此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM