[英]Log4j2 JSON Layout: add custom date field in UTC
Log4j2支持JSON布局 ,我在log4j2.xml中添加了一個額外的自定義字段:
<JsonLayout compact="true" eventEol="true" stacktraceAsString="true">
<KeyValuePair key="@timestamp" value="$${date:yyyy-MM-dd'T'HH:mm:ss.SSS'Z'}"/>
</JsonLayout>
通常,一切正常,但是此日志由Filebeats處理,並且假定該日期以UTC表示。
所有日志條目的日期值都在本地時區。
是否可以通過某種方式在UTC中輸出日期?
您可以創建自己的查找 ,因為您已經知道, KeyValuePair
在您共享的手冊頁的 value屬性中支持查找。
出於示例目的,我創建了一個使用System.currentTimeMillis()的簡單查找。
這是示例代碼:
首先,查找類:
package utcTime;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;
@Plugin(name = "UtcMillis", category = "Lookup")
public class UtcMillisLookup implements StrLookup{
/**
* Lookup the value for the key.
* @param key the key to be looked up, may be null
* @return The value for the key.
*/
public String lookup(String key) {
return String.valueOf(getUTCMillis());
}
/**
* @return current UTC time in milliseconds
*/
private long getUTCMillis(){
return System.currentTimeMillis();
}
/**
* Lookup the value for the key using the data in the LogEvent.
* @param event The current LogEvent.
* @param key the key to be looked up, may be null
* @return The value associated with the key.
*/
public String lookup(LogEvent event, String key) {
return String.valueOf(getUTCMillis());
}
}
接下來,log4j2.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<JsonLayout compact="true" eventEol="true" stacktraceAsString="true">
<KeyValuePair key="@timestamp" value="$${UtcMillis:}"/>
</JsonLayout>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
需要注意的是,查找沒有參數/鍵,以便你可以離開的那部分空白/空,但你仍然必須使用冒號( :
),這就是為什么你看到$${UtcMillis:}
在上面的配置。
最后,一個簡單的類生成一個日志事件:
package utcTime;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class MainUtcLookup {
private static final Logger log = LogManager.getLogger();
public static void main(String[] args){
log.info("Here's some info!");
}
}
這是示例輸出:
{
"thread":"main",
"level":"INFO",
"loggerName":"utcTime.MainUtcLookup",
"message":"Here's some info!",
"endOfBatch":false,
"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger",
"instant":{
"epochSecond":1534642997,
"nanoOfSecond":556000000
},
"threadId":1,
"threadPriority":5,
"@timestamp":"1534642997558"
}
我不會深入研究以UTC毫秒為單位的當前時間的所有不同方式的細節,因為我敢肯定您可以自己研究細節。 我只是想提供一個示例,說明如何實現將毫秒級時間戳添加到log4j2 JSONLayout
主要目標。
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.