logger.js 1.33 KB
const {transports, createLogger, format} = require('winston');
const config = require('../config/index');
const isProduction = process.env.NODE_ENV === 'production';

require('winston-daily-rotate-file');

module.exports = (loggers) => {
  const tps = loggers.map(log => {
    switch (log.type) {
      case 'console':
        return new transports.Console(Object.assign({
          level: 'info'
        }, log));
      case 'file':
        return new transports.File(Object.assign({
          level: 'info',
          zippedArchive: true,
          maxsize: 209715200, // 200m
          maxFiles: 7,
        }, log));
      case 'dailyfile':
        return new transports.DailyRotateFile(Object.assign({
          level: 'info',
          zippedArchive: true,
          maxSize: '200m',
          maxFiles: '7d',
          datePattern: 'YYYY-MM-DD',
          dirname: isProduction ? '/home/spider-ufo/logs' : './logs'
        }, log));
      default:
        return void 0;
    }
  });

  const logger = createLogger({
    level: 'info',
    format: format.combine(
      format.timestamp({
        format: () => {
          return new Date().toLocaleString();
        }
      }),
      format.printf(info => `${info.level}: ${info.message}`)
    ),
    transports: tps
  });

  return logger;
};

module.exports.logger = module.exports(config.loggers);