Winston: how to rotate logs

无人久伴 提交于 2019-11-28 18:11:54

winston author and maintainer here.

Logging to a new file everyday is currently an open feature request: https://github.com/flatiron/winston/issues/10. Would love to see someone implement it.

That said, there are other options:

  1. The File transport accepts a maxsize option which will rotate the logfile when it exceeds a certain size in bytes.

  2. There is also an open pull-request with a new transport I haven't had a chance to really dig into "fileRotate", which it seems does this kind of date-based rotation: https://github.com/flatiron/winston/pull/120/files

The feature is present and we are using it in production, winston.transports.DailyRotateFile:

var timeFormatFn = function() {
    'use strict';
    return moment().format(cfg.timeFormat);
};

var logger = new(winston.Logger)({
    exitOnError: false,
    transports: [
        new(winston.transports.DailyRotateFile)({
            filename: cfg.appLogName,
            dirname: __dirname + '/../' + cfg.logsDirectory,
            datePattern: cfg.rollingDatePattern,
            timestamp: timeFormatFn
        }),
        new(winston.transports.Console)({
            colorize: true,
            timestamp: timeFormatFn
        })
    ]
});

According to the author of winston-filerotatedate it is a:

File transport for winston that allows the log files to be rotated depending on size and time.

The File transport accepts a filename via the 'filename' option and uses that file as the primary logging target. Should the file grow past 'maxsize' bytes then the current log file is renamed and a new primary log tile is created. The name of the renamed log file is formated as such 'basenameYYYYMMDD[a-z].bak'.

Available options are:

  • level: Level of messages that this transport should log.
  • silent: Boolean flag indicating whether to suppress output.
  • timestamp: Boolean flag indicating if we should prepend output with timestamps (default true). If function is specified, its return value will be used instead of timestamps.
  • filename: The filename of the logfile to write output to.
  • dirname: The folder the logfile will be created in.
  • maxsize: Max size in bytes of the logfile, if the size is exceeded then a new file is created.
  • json: If true, messages will be logged as JSON (default true).

As of Dec 18, 2012, this feature is now available in Winston (see https://github.com/flatiron/winston/pull/205)

izhar ahmad

You can use the following code to rotate the log files daily:

var winston = require('winston');
require('winston-daily-rotate-file');
var transport = new (winston.transports.DailyRotateFile)({
    filename: './log',
    datePattern: 'yyyy-MM-dd.',
    prepend: true,
    level: info
});
var logger = new (winston.Logger)({
    transports: [
      transport
    ]
});
logger.info('Hello World!');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!