[英]log4j2: custom formating for pattern parameter
通常日志記錄如下所示:
Duration duration = ...;
log.info("Duration: {}", duration);
但是,如果您需要自定義格式怎么辦?
if (log.isInfoEnabled()) {
String value = duration.toSeconds() + "." + duration.toMillis();
log.info("Duration: {}", value);
}
在這種情況下,代碼很復雜。 我正在尋找一種方法來進行第一個示例中的簡單日志記錄,但能夠使用某種機制自定義值格式,例如,為給定類型定義格式 function:
LogSystem.install(Duration.class, duration -> {
return String.format("%d.%d", duration.toSeconds(), duration.toMillis();
});
問題:
if (log.isInfoEnabled()) {... }
以某種方式簡化嗎?log4j 2.x 有這樣或類似的功能嗎?
是的,您可以使用
log.info("Duration: {}.{}", duration.toSeconds(), duration.toMillis());
您可以傳遞任意數量的參數。 如果使用參數化日志記錄,則不需要檢查 log.isInfoEnabled()。
它可能存在於其他日志庫中嗎?
SLF4j 還支持參數化日志記錄。
是的,您可以使用屬性文件來執行此操作。在 log4j2.properties 文件中設置策略模式,例如:
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ABClog/ABCapplication.log
appender.rolling.filePattern = ABClog/ABCapplication.%d{dd-MMM}.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = { [%-5level %d{dd-MM-yyyy hh:mm:ss.SSS } ] [%msg] }%n
在 log4j2.proerties 文件中設置上述配置后,您將獲得所需的 output,即使使用屬性文件概念,您也可以添加額外信息,例如 Correlation-ID
log.info("hello")
更多模式樣式的 Log4j2 文檔: https://logging.apache.org/log4j/2.x/manual/layouts.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.