gpt4 book ai didi

java - Log4J 的默认 MessageFactory 是什么

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:52 27 4
gpt4 key购买 nike

org.apache.logging.log4j.Logger 的文档说

   /**
* Logs a message with parameters at the given level.
*
* @param level the logging level
* @param message the message to log; the format depends on the message factory.
* @param params parameters to the message.
* @see #getMessageFactory()
*/
void log(Level level, String message, Object... params);

但是:

  1. 当我没有设置时使用哪个 MessageFactory?
  2. 哪种消息格式使用默认工厂?
  3. 如果默认工厂无法满足我的需求,我该如何设置自己的工厂?

更新:

请在答案中添加类名和 XML 元素名。如果没有适当的搜索词,很难在 Google 上找到有关 Log4J 2.x 的任何信息。

最佳答案

  1. 如果您不设置消息工厂,则默认使用 ParameterizedMessageFactory
  2. 默认情况下,log4j 为参数化消息使用消息工厂,因此您可以执行 logger.warn("hello {}", user.getName());
  3. 当您获得记录器时,您可以通过调用 LogManager.getLogger(name, messageFactory) 来设置您自己的工厂。

如果您想要 String.format 类型的参数(System.out.printf 格式),您可以使用 LogManager.getLogger(MyClass.class, new StringFormatterMessageFactory()) 来获取记录器。

如果您最常见的用法是参数化消息({} 格式),但如果您偶尔想要更多地控制字符串格式化程序提供的输出格式,您可以正常声明您的记录器(因此它使用 {} 参数化消息),并使用 Logger.printf 方法。

例子:

class MyClass {
private static Logger logger = LogManager.getLogger(MyClass.class);

public void someMethod() {
// use printf here to precisely control the number of digits displayed
logger.printf(Level.INFO, "pi: %.5f", Math.PI);
}
}

这一切都在代码中。不涉及配置(XML 或其他)。

关于java - Log4J 的默认 MessageFactory 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25845120/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com