Use log4j expansion pack RollingFileAppender generate a log file timestamped
Blog Category: the Java
DailyRollingFileAppender resulting file is not time-stamped, must, after a certain point in time, my son had to rename a file-stamped.
For example timestamps accurate to the hour, the format .yyyy-MM-dd-HH, 2011-05-05 current time is 5:00, then the logs for
log
after the time becomes 6:00 (6:00 and have access to the log), the log to
log
log.2011-05-05-05
because log4j event is triggered if a certain period of time does not log access, even to the point of time, it will not add a timestamp to rename. For example, two days later have access to the log, then only produce log.2011-05-05-05 this file. This will cause the log statistics, statistics not see this document.
The solution is to generate a log file when it is already stamped. Such as 5:00, when the log is already log.2011-05-05-05. Original log4j does not implement this feature, you need to implement a succession FileAppender own Appender. I looked at the source code, you can refer DailyRollingFileAppender, modify its constructor and rollOver. I did not go to experiment, do not know can not succeed.
apache-log4j-extras log4j is extended package, which can achieve this requirement TimeBasedRollingPolicy.
Required packages:
log4j-1.2.15.jar
Apache-log4j-Extras-1.0.jar
Note: log4j 1.2.15 must be above 14 not
log4j Properties profile can not be used, must be used xml. Configuration, see:
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
- <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
- <!-- appender -->
- <!-- STDOUT -->
- <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern" value="%d %p [%c] - %m%n" />
- </layout>
- </appender>
- <!-- FILE -->
- <appender name="FILE"
- class="org.apache.log4j.rolling.RollingFileAppender">
- <rollingPolicy
- class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
- <param name="FileNamePattern"
- value="d:/logs/file.%d{yyyy-MM-dd-HH}" />
- </rollingPolicy>
- <layout class="org.apache.log4j.PatternLayout">
- <param name="ConversionPattern"
- value="%m%n" />
- </layout>
- </appender>
- <logger name="view">
- <level value="info" />
- <appender-ref ref="FILE" />
- </logger>
- <root>
- <level value="info" />
- <appender-ref ref="STDOUT" />
- </root>
- </log4j:configuration>
Note: org.apache.log4j.rolling.RollingFileAppender is rolling under the package, rather than the original org.apache.log4j.RollingFileAppender
test case:
- public static void main(String[] args) {
- Logger logger = Logger.getLogger("view");
- logger.info("test");
- }
The use of reference TimeBasedRollingPolicy:
http://logging.apache.org/log4j/companions/extras/apidocs/org/apache/log4j/rolling/TimeBasedRollingPolicy.html