Is it possible to configure log4j to create a new

2019-01-18 20:39发布

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.

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.

Is this possible? If so, how?

标签: java log4j
4条回答
Rolldiameter
2楼-- · 2019-01-18 20:51

Solution with 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 OnStartupTriggeringPolicy and %i in filePattern. This way, Log4j will create new log file with index each time you run App.

查看更多
仙女界的扛把子
3楼-- · 2019-01-18 20:53

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.

查看更多
Fickle 薄情
4楼-- · 2019-01-18 21:01
劳资没心,怎么记你
5楼-- · 2019-01-18 21:02

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/

**Edit:**I got one more solution! But no idea whether it works or not,but you can try http://www.mail-archive.com/log4cxx-user@logging.apache.org/msg02132.html

查看更多
登录 后发表回答