Nodejs日志库winston配置

为什么80%的码农都做不了架构师?>>>   hot3.png

const config = require('config');
const winston = require('winston');
const path = require('path');
const dailyRoateFile = require('winston-daily-rotate-file');

// logger directory
let defaultLogDir = 'logs';
if (config.has('logger.path')) {
  defaultLogDir = config.get('logger.path');
}
const logDir = path.join(path.dirname(__dirname), defaultLogDir);

// logger exception file
const exceptionFile = path.join(logDir, 'exceptions.log');
// logger error file
const errorFile = path.join(logDir, 'error.log');
// logger app file
const logFile = path.join(logDir, 'app-%DATE%.log');

// logger level
let defaultLogLevel = 'debug';
if (config.has('logger.level')) {
  defaultLogLevel = config.get('logger.level');
}

// logger rotate maxSize
let defaultMaxSize = '50m';
if (config.has('logger.maxSize')) {
  defaultMaxSize = config.get('logger.maxSize');
}
// logger rotate maxFiles
let defaultMaxFiles = '14d';
if (config.has('logger.maxFiles')) {
  defaultMaxFiles = config.get('logger.maxFiles');
}

// logger formatter
const formatter = winston.format.combine(
  // string use util.format
  winston.format.splat(),
  // timestamp to format
  winston.format.timestamp({
    format: 'YYYY-MM-DD HH:mm:ss.SSS'
  }),
  winston.format.printf(info => {
    return `${info.timestamp} ${info.level}:${info.message}`;
  })
);

// logger transports
const logTransports = [
  new winston.transports.File({
    level: 'error',
    filename: errorFile
  }),
  new dailyRoateFile({
    filename: logFile,
    datePattern: 'YYYY-MM-DD-HH',
    maxFiles: defaultMaxFiles,
    maxSize: defaultMaxSize
  })
];

// create logger instance
const logger = winston.createLogger({
  level: defaultLogLevel,
  format: formatter,
  transports: logTransports,
  exceptionHandlers: [
    new winston.transports.File({
      filename: exceptionFile
    })
  ],
  exitOnError: false
});

if (process.env['NODE_ENV'] !== 'production') {
  logger.add(new winston.transports.Console({
    format: formatter
  }));
}

module.exports = logger;

 

转载于:https://my.oschina.net/thmz/blog/3035320

你可能感兴趣的:(Nodejs日志库winston配置)