Javide
Javide

Reputation: 2637

log4j DailyRollingFileAppender does not create file with date pattern

Using org.apache.log4j in a Java 8 application, I want a new log file to be created every hour with name e.g.: "mylog.log.2014-09-24-18". I read I need to use DailyRollingFileAppender, but when I start the application the log file is named "mylog.log".

This is the content of my log4j.properties file:

# Set root logger level and its appenders
log4j.rootLogger=DEBUG, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH
log4j.appender.file.Append=true
log4j.appender.file.File=mylog.log
log4j.appender.file.encoding=UTF-8
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Can you please let me know how I can achieve this?

Upvotes: 4

Views: 10933

Answers (2)

Adrian Shum
Adrian Shum

Reputation: 40036

From my understanding, what you are looking for is, you want the active log file already create with date/time in the file name, and once rolling is required, it will simply log to a new file with latest date/time in file name.

If my understanding is correct I wonder if log4j 1.x can do what you are looking for.

Log4J is simply writing to mylog.log and upon rolling, it move the original mylog.log to mylog.log.yyyy-mm-dd and then create a new mylog.log again.

If you are using SLF4J, and if there is no special reason for you to stick to Log4J as backend, Logback actually is providing what you are looking for:

http://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy

Omit the file property in RollingFileAppender, and setup the file pattern in the TimeBasedRollingPolicy. The way log files are created will be what you are expecting.

Upvotes: 3

Perry Zhao
Perry Zhao

Reputation: 78

I set the DatePattern to log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm, when I logged first time, the log wrote into mylog.log, and one minute later, log wrote into mylog.log.2014-09-24-10-42. So i think the first time your log will write into mylog.log, and an hour later, the system will generate a file named 'mylog.log.2014-09-24-10'.

Upvotes: 5

Related Questions