Java 是否可以配置 log4j 以在每次运行应用程序时创建一个新文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1444520/
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-08-12 12:21:35  来源:igfitidea点击:

Is it possible to configure log4j to create a new file with every run of the application?

javalog4j

提问by Thomas Owens

For example, the first time I run an application (or immediately after I clear out the /logs directory), I want log4j to write the application's logs to a file called log.0. Then, I exit the application and restart it, I want the logs to be written to log.1. And so on.

例如,我第一次运行应用程序时(或在我清除 /logs 目录后立即运行),我希望 log4j 将应用程序的日志写入名为 log.0 的文件。然后,我退出应用程序并重新启动它,我希望将日志写入 log.1。等等。

I would like to keep this in the configuration file, although if I can't, I guess I could always do it in my application, when log4j is set up.

我想将其保留在配置文件中,但如果我不能,我想我总是可以在设置 log4j 时在我的应用程序中做到这一点。

Is this possible? If so, how?

这可能吗?如果是这样,如何?

采纳答案by Umesh

May be this is what you are looking for

可能这就是你要找的

http://veerasundar.com/blog/2009/08/how-to-create-a-new-log-file-for-each-time-the-application-runs/

http://veerasundar.com/blog/2009/08/how-to-create-a-new-log-file-for-each-time-the-application-runs/

**Edit:**I got one more solution! But no idea whether it works or not,but you can try http://www.mail-archive.com/[email protected]/msg02132.html

**编辑:**我还有一个解决方案!但不知道它是否有效,但您可以尝试 http://www.mail-archive.com/[email protected]/msg02132.html

回答by Karl

Off the top of my head I don't think this is possible from with Log4j. Maybe when you shut the application down you could rename the .log file so next time you start up a new log file is created.

在我的脑海中,我认为 Log4j 不可能做到这一点。也许当您关闭应用程序时,您可以重命名 .log 文件,以便下次启动时创建一个新的日志文件。

回答by Ceki

See logback's manual on uniquely named files (by timestamp).

请参阅有关唯一命名文件的logback 手册(按时间戳)

回答by Nazar Ostryzhniuk

Solution with log4j2:

使用 log4j2 的解决方案:

        <RollingFile name="RollingFile" fileName="${log-path}/GScraper.log"
                 filePattern="${log-path}/GScraper_%d{yyyy-MM-dd}_%i.log">
        <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
        <PatternLayout>
            <pattern>%level\t%d{yyyy-MM-dd HH:mm:ss} %c: %m%n</pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            <SizeBasedTriggeringPolicy size="32 MB" />
            <OnStartupTriggeringPolicy/>
        </Policies>
    </RollingFile>

Note OnStartupTriggeringPolicyand %iin filePattern. This way, Log4j will create new log file with index each time you run App.

注意OnStartupTriggeringPolicy%我filePattern。这样,每次运行 App 时,Log4j 都会创建带有索引的新日志文件。