[英]Log4J2 - How to prevent it from appending?
這是我的 log4j2 配置:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="MyFile" fileName="logs\application.log" append="false">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" level="error" />
<AppenderRef ref="MyFile" level="info"/>
</Root>
</Loggers>
</Configuration>
以下是 Log4J2 輸出到我的文件的方式:
2020-07-15 12:09:40.449 [main] WARN [MYAPP] - Values don't match:
First Map Key: [MYKEY] - First Map Value: [MYVALUE]
Second Map Key: [MYKEY] - Second Map Value: [MYVALUE]
2020-07-15 12:09:40.449 [main] WARN [MYAPP] - Values don't match:
First Map Key: [MYKEY] - First Map Value: [MYVALUE]
Second Map Key: [MYKEY] - Second Map Value: [MYVALUE]
Values don't match:
First Map Key: [MYKEY] - First Map Value: [MYVALUE]
Second Map Key: [MYKEY] - Second Map Value: [MYVALUE]
...
在我的代碼中; 我正在通知 Logger 和 Formatter:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
private static final Logger logger = LogManager.getLogger([CURRENT_JAVA_CLASS].class);
private static final Formatter formatter = new Formatter();
...
formatter.format("Values don't match: \n First Map Value: %s \n Second Map Value: %s \n",
firstMapEntry.getValue(),secondMapEntry.getValue());
logger.warn(formatter);
我不希望它這樣做,我只想讓它 output 最新的錯誤,而不是將它與前面的行連接起來。 誰能告訴我該怎么做?
我不得不想知道你為什么要這樣做。 你可以這樣做:
logger.warn("Values don't match: \n First Map Value: {} \n Second Map Value: {} \n", firstMapEntry.getValue(), secondMapEntry.getValue());
或者
StringFormattedMessage msg = new StringFormattedMessage("Values don't match: \n First Map Value: %s \n Second Map Value: %s \n", firstMapEntry.getValue(), secondMapEntry.getValue());
logger.warn(msg);
或者
private static final Logger logger = LogManager.getFormatterLogger([CURRENT_JAVA_CLASS].class);
logger.warn("Values don't match: \n First Map Value: %s \n Second Map Value: %s \n", firstMapEntry.getValue(), secondMapEntry.getValue());
第一個選項表現最好。 即使不記錄消息,您的示例也會格式化字符串。 如果將記錄事件,上述所有替代方案只會格式化字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.