Unable to append the date to the file name using l

2019-05-11 15:15发布

问题:

Hi I am trying to append the current date to the file name using log4j DailyRollingFileAppender, but its not working. I have used the configuration like below. Please suggest a solution for this

properties

log4j.rootLogger = DEBUG, rollingAppender
log4j.appender.rollingAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.rollingAppender.DatePattern='.'yyyy-MM-dd
log4j.appender.rollingAppender.File=F:/temp/app.log
log4j.appender.rollingAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingAppender.layout.ConversionPattern=[%p] %d %c %M - %m%n

I am expecting the log file as app2014-11-07.log, but its still app.log

回答1:

If you're using log4j 1.x, we strongly recommend that you use org.apache.log4j.rolling.RollingFileAppender 1 instead of org.apache.log4j.DailyRollingFileAppender (may lose messages, Bug 43374).

So the configuration of you appender can be:

log4j.rootLogger = DEBUG, rollingAppender
log4j.appender.rollingAppender=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.rollingAppender.rollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.rollingAppender.rollingPolicy.fileNamePattern=F:/temp/app%d{yyyy-MM-dd}.log
log4j.appender.rollingAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingAppender.layout.ConversionPattern=[%p] %d %c %M - %m%n

Notes

  1. In that case, you need to add the respective jar (apache-log4j-extras-1.2.17.jar).


回答2:

DailyRollingFileAppender means archiving log files.
For example, today is 2014.11.07, when you first run your app, your log file name would be app.log. Tomorrow, you run the app again,it's log file also named app.log, but yesterday's log file has been changed , maybe like app.log.2014.11.07

Try this :

  1. Change your System Date, to be 2014.11.08
  2. Run your app, then check out the log-path:F:/temp/

OR

Change this

    log4j.appender.rollingAppender.DatePattern='.'yyyy-MM-dd

to

    log4j.appender.rollingAppender.DatePattern='.'yyyy-MM-dd-HH-mm

That means it will produce a new log file minute-by-minute.
Run it again.



回答3:

You can use this configuration:

log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.stdout.layout=org.apache.log4j.HTMLLayout
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%d](%F:%L) - %m%n
#log4j.appender.stdout.File=/usr/tomcat7/webapps/ngp/newgen.log
log4j.appender.stdout.File=c:/logs/DSP.log
#log4j.appender.stdout.DatePattern='.'yyyy-MM-dd
log4j.appender.stdout=org.apache.log4j.RollingFileAppender
log4j.appender.stdout.MaxBackupIndex=1
log4j.appender.stdout.append=false