java 如何将日期时间戳添加到 log4j2 日志文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31670088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:57:55  来源:igfitidea点击:

How to add the date timestamp to log4j2 logfiles?

javalog4jlog4j2

提问by membersound

I want to create day dependent logfiles with log4j2:

我想创建与日相关的日志文件log4j2

<RollingFile name="APP" fileName="application-%d{yyyy-MM-dd}.log" />

Resulting logfile name: application-%d{yyyy-MM-dd}.log, the timestamp is not replaced. Why?

结果日志文件名:application-%d{yyyy-MM-dd}.log,时间戳不被替换。为什么?

采纳答案by Loganathan Mohanraj

The pattern should not be given in the attribute "fileName" rather you have to specify the pattern in the attribute "filePattern" as like below.

模式不应在属性“fileName”中给出,而必须在属性“filePattern”中指定模式,如下所示。

<RollingFile name="RollingFile" fileName="${log-path}/filename.log" 
filePattern="${log-path}/filename-%d{yyyy-MM-dd}-%i.log" >
...
...
</RollingFile>

The "%i" is the counter that will be automatically incremented in rollover.

“%i”是将在翻转时自动递增的计数器。

Hope this will help you.

希望这会帮助你。

回答by Bishal Gupta

To append the filename with date, replace %d with below format, i was having the same problem and but got by doing so :

要用日期附加文件名,用以下格式替换 %d,我遇到了同样的问题,但这样做了:

<RollingFile name="APP" fileName="application-${date:yyyy-MM-dd}.log" />

回答by Gre?anu Emanuel - Vasile

Try this:

试试这个:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">

    <Properties>
        <Property name="log-path">D:/logs/</Property>
    </Properties>

    <Appenders>

        <RollingFile name="DebuggerLogger" fileName="${log-path}CMSAutomation.${date:yyyy-MM-dd_hh-mm-ss}.log" filePattern="${log-path}/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="10 MB" />
            </Policies>
        </RollingFile>

    </Appenders>

    <Loggers>
        <Root level="ALL">
            <AppenderRef ref="DebuggerLogger"/>
        </Root>
    </Loggers>

</Configuration>

回答by Ali

Use ASizeBasedTriggeringPolicyclass in appender. You can even append the current second to the logfile name. %d{yyyy_MM_dd HH.mm.ss}

ASizeBasedTriggeringPolicy在 appender 中使用class。您甚至可以将当前秒附加到日志文件名。%d{yyyy_MM_dd HH.mm.ss}

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.rolling.*;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.config.plugins.PluginAttribute;
import org.apache.logging.log4j.core.config.plugins.PluginFactory;

@Plugin(name = "ASizeBasedTriggeringPolicy",
        category = "Core",
        printObject = true
)
public class ASizeBasedTriggeringPolicy extends AbstractTriggeringPolicy {
    private SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy;
    private RollingFileManager aManager;

    protected ASizeBasedTriggeringPolicy(String maxFileSize) {
        sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy(maxFileSize);

    }

    public void initialize(RollingFileManager aManager) {
        sizeBasedTriggeringPolicy.initialize(aManager);
        this.aManager = aManager;
    }

    public boolean isTriggeringEvent(LogEvent event) {
        if (sizeBasedTriggeringPolicy.isTriggeringEvent(event)) {
            aManager.getPatternProcessor().setPrevFileTime(System.currentTimeMillis());
            return true;
        } else {
            return false;
        }
    }

    @PluginFactory
    public static ASizeBasedTriggeringPolicy createPolicy(@PluginAttribute("size") String size) {
        return new ASizeBasedTriggeringPolicy(size);
    }
}

Then use ASizeBasedTriggeringPolicyin log appender

然后ASizeBasedTriggeringPolicy在日志追加器中使用

<RollingFile name="complete-log" fileName="${log-path}/complete-${date:yyyy_MM_dd HH.mm.ss} .log" 
                 filePattern="${log-path}/app-complete-%d{yyyy_MM_dd HH.mm.ss} - %i.log" >
    ...
    ... 
    <Policies>
         <ASizeBasedTriggeringPolicy size="200 kB"  />
    </Policies>
</RollingFile>

回答by Alferd Nobel

In yaml check the Property filePatterndefined as "${date:yyyy-MM-dd}", which helps to tag the date. If you are interested to tag the HOSTNAMEenvironment variable to date then : "${env:HOST}-${date:yyyy-MM-dd}"

在 yaml 中检查filePattern定义为的属性"${date:yyyy-MM-dd}",这有助于标记日期。如果您有兴趣将HOSTNAME环境变量标记为最新,则:"${env:HOST}-${date:yyyy-MM-dd}"

Properties:
    Property:
      - name: log-path
        value: "logs"
      - name:  filePattern
        value: "${date:yyyy-MM-dd}"

  Appenders:

    Console:
      name: Console_Appender
      target: SYSTEM_OUT
      PatternLayout:
        pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

    File:
      name: File_Appender
      fileName: "${log-path}/filelog-${filePattern}.log"

      PatternLayout:
        pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

    RollingFile:
      - name: RollingFile_Appender
        fileName: "${log-path}/rollingfile-${filePattern}.log"
        filePattern: "logs/archive/rollingfile.log.%d{yyyy-MM-dd-hh-mm}.gz"
        PatternLayout:
          pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"