2

Starting from the current log4j configuration:

log4j.rootLogger=debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=logs/file.log

log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

How could I add a date or a timestamp as part of the filename? I tried to use RollingDateFileAppender as described here, but with no success (and also some properties like MaxBackupIndex and MaxFileSize are unsupported). Note that I would like to include a date in the format 20121102143402781 (compact) or Unix_Mills 1351866842781.

Community
  • 1
  • 1
vdenotaris
  • 13,297
  • 26
  • 81
  • 132

3 Answers3

1

You can set FileAppender dynamically

SimpleLayout layout = new SimpleLayout();           
FileAppender appender = new FileAppender(layout,"logname."+new Date().getTime(),false);
logger.addAppender(appender); 
SANN3
  • 9,459
  • 6
  • 61
  • 97
0

You can use DailyRollingFileAppender

log4j.rootLogger=debug, R
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.encoding=UTF-8
log4j.appender.R.File=logs/file.log
log4j.appender.R.DatePattern='-'yyyy-MM-dd
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%p] [%t] [%c] %m%n
Feiyu Zhou
  • 4,344
  • 32
  • 36
  • This will add the date on rolling. As far as I understood, OP wants also the current logfile to have a date. (Please correct me if wrong @vdenotaris ) – Fildor Sep 28 '15 at 11:20
  • I have looked the log4j API but didn't see any options – Feiyu Zhou Sep 28 '15 at 13:21
  • You can read this question, it's same demand with your op's. http://stackoverflow.com/questions/192456/setting-a-log-file-name-to-include-current-date-in-log4j – Feiyu Zhou Sep 28 '15 at 13:29
-3

I got totally excited about creating a custom Layout, but turns out PatternLayout already contains the features you need :-( You need to do something like this:

log4j.appender.R.layout.ConversionPattern="%d{yyyyMMddHHmmss} %p %t %c - %m%n

%d acesses the current date, the content of the curly brackets is a Simple Date Format, which you can customize to meet your needs.

Simon Eismann
  • 273
  • 1
  • 5
  • 17