Date rolling file appender

Rob Gagnon edited this page May 13, 2015 · 6 revisions

This appender will log to a file, moving old log messages to timestamped files according to a specified pattern. For example, if log4js was configured with the following json file:

{ "appenders": [ {
    "type": "dateFile",
    "filename": "blah.log",
    "pattern": "-yyyy-MM-dd",
    "alwaysIncludePattern": false
  } ]

Then initial logging would create a file called "blah.log". At midnight, the current "blah.log" file would be renamed to "blah.log-2012-09-26" (for example), and a new "blah.log" file created.

The following strings are recognised in the pattern:

  • yyyy - the full year, use yy for just the last two digits
  • MM - the month
  • dd - the day of the month
  • hh - the hour of the day (24-hour clock)
  • mm - the minute of the hour
  • ss - seconds
  • SSS - milliseconds (although I'm not sure you'd want to roll your logs every millisecond)
  • O - timezone (capital letter o)

Note that a new file is started whenever the pattern for the current log entry differs from that of the previous log entry.

Example 2 - Hourly log files kept for 1 month.


The current file is always calibrate.log. At rollover (anytime a log entry is recorded where the evaluated pattern differs from the previous evaluated pattern, the new filename is calculated by appending the evaluated pattern to the filename - e.g. logs/calibrate.log-17--14.log. If this file exists already (perhaps from the previous month) it will be deleted. Then the current file will be renamed to the new filename, and a new calibrate.log will be started.

Note that this doesn't guarantee that files will be erased after one month. For example, when rolling from Jan 31 to Feb 1, the files for 31st would remain in place until 31 March.