In this post, I am sharing how to rotate Winston log files based on time.

Among many different logging transports, Winston provides winston.transports.DailyRotateFile transport class for outputting to a local log file and rotating the log file based on time e.g. every year, day, hour etc.

Rolling time depends on datePattern option provided to DailyRotateFile instance. Note that the date pattern will become a suffix of a log file.

In the following example log files will be rotated every hour:

var winston     = require ('winston'),
    path        = require ('path'),
    transports  = [];

transports.push(new winston.transports.DailyRotateFile({
  name: 'file',
  datePattern: '.yyyy-MM-ddTHH',
  filename: path.join(__dirname, "logs", "log_file.log")

var logger = new winston.Logger({transports: transports});

// ... and logging"log information", {extraData: 'somve_value'});

As mentioned above, log file names is composed of log file name from filename option and suffix from datePattern option e.g. log_file.log.2013-12-17T16, log_file.log.2013-12-17T17.

Default date pattern is .yyyy-MM-dd which rotate logs file every day at midnight.

Available date pattern tokens

All available date pattern tokens which can be used in datePattern option are as follows:

  • yy - last two digits of the current year e.g. 14 for 2014
  • yyyy - year (4 digits) e.g. 2014
  • M - unpadded month e.g. 1 for January, 12 for December
  • MM - padded month (starting from 1) e.g. 01 for January, 12 for December
  • d - unpadded day of a month e.g. 1 for 1st, 10 for 10th
  • dd - padded day of a month e.g. 01 for 1st, 10 for 10th
  • H - unpadded hour e.g. 1 for 1 AM
  • HH - padded hour e.g. 01 for 1 AM
  • m - unpadded minute e.g. 0, 1, 2, ... 58, 59
  • mm - padded minute e.g. 00, 01, 02, ... 58, 59

Note that you can't rotate files more frequent then every minute e.g. every second, using winston.transports.DailyRotateFile class.

You can also refere to Stack Overflow It is possible to do hourly log rotation in Winston? question discussing the same problem.