Log4j2 JSON 布局:添加 UTC 中的自定义日期字段

2024-01-20

Log4j2 支持JSON 布局 https://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout,我在 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 格式输出日期?


You can 创建您自己的查找 https://logging.apache.org/log4j/2.0/manual/extending.html#Lookups因为,我相信你已经知道了,KeyValuePair支持根据其值属性进行查找您共享的手册页 https://logging.apache.org/log4j/2.x/manual/layouts.html#JSONLayout.

出于示例目的,我创建了一个简单的查找,使用System.currentTimeMillis() https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#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.

希望这可以帮助!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Log4j2 JSON 布局:添加 UTC 中的自定义日期字段 的相关文章

随机推荐