how to pass a filename to winston logger?

2019-08-12 17:48发布

I have winston set up as a logger and it works great. However, I have several processes that I would like to log to different files. How can I pass the filename into a logger instance?

I am using this as my block

'use strict';
const { createLogger, format, transports } = require('winston');
require('winston-daily-rotate-file');
const fs = require('fs');
const path = require('path');
const logDir = '/codeforge/log';

const dailyRotateFileTransport = new transports.DailyRotateFile({
  filename: `${logDir}/%DATE%-engine.log`,
  maxSize: "1g",
  maxDays: "3d",
  zippedArchive: true,
  datePattern: 'YYYY-MM-DD'
});

const logger = createLogger({
  // change level if in dev environment versus production
  level: 'debug', 
  maxsize: '500m',
  format: format.combine(
    format.timestamp({
      format: 'YYYY-MM-DD HH:mm:ss'
    }),
    // for the log file
    format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
  ),
  transports: [
    new transports.Console({
      level: 'info',
      format: format.combine(
        format.colorize(),
        format.printf(
          info => `${info.message}`
        )
      )
    }),
    dailyRotateFileTransport
  ]
});

module.exports = logger

I would like to pass in a filename to replace the "-engine" part to create or append a log file for it.

thanks for any tips.

1条回答
Viruses.
2楼-- · 2019-08-12 18:42

Make your logger into a function that you call like

const log = require('logger')('myfilename');

Code:

'use strict';
const { createLogger, format, transports } = require('winston');
require('winston-daily-rotate-file');
const fs = require('fs');
const path = require('path');
const logDir = '/codeforge/log';

const dailyRotateFileTransport = filename => new transports.DailyRotateFile({
  filename: `${logDir}/%DATE%-${filename}.log`,
  maxSize: "1g",
  maxDays: "3d",
  zippedArchive: true,
  datePattern: 'YYYY-MM-DD'
});

const logger = function(filename){
  return createLogger({
    // change level if in dev environment versus production
    level: 'debug', 
    maxsize: '500m',
    format: format.combine(
      format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss'
      }),
      // for the log file
      format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
    ),
    transports: [
      new transports.Console({
        level: 'info',
        format: format.combine(
          format.colorize(),
          format.printf(
            info => `${info.message}`
          )
        )
      }),
      dailyRotateFileTransport(fileName)
    ]
  });
}

module.exports = logger // is now a function
查看更多
登录 后发表回答