带有最大尺寸和每日旋转的winston的多个日志文件

时间:2017-10-13 14:30:34

标签: javascript node.js typescript logging winston

现在我使用winston记录最大尺寸和每日轮换次数

我希望每个API端点有一个文件,因此定义了多个日志文件

我怎么能实现这个目标?

这是我的winston助手类

import * as winston from 'winston';
import { config } from '../config';

export const logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
      timestamp: () => (new Date().toLocaleTimeString()),
      colorize: true,
      level: config.application.mode === 'test' ? 'emerg' : 'info',
    }),
    new (require('winston-daily-rotate-file'))({
      filename: `${process.cwd()}${config.application.log.dir}/.log`,
      timestamp: () => (new Date().toLocaleTimeString()),
      datePattern: 'yyyy-MM-dd',
      prepend: true,
      level: config.application.mode === 'test' ? 'emerg' : 'info',
      maxsize: 100000000, // en octet
      colorize: false,
      json: false,
    }),
  ],
});

export const generateLog = function (data: object): string {
  let log = 'id="easy_tms" ';
  for (const key in data) {
    const value = (data[key] !== undefined && data[key] !== null) ? data[key] : '';
    if (value instanceof Date) {
      log += key + '="' + value.toISOString() + '" ';
    } else if (Array.isArray(value) === true) {
      log += key + '="' + value.join(',');
    } else {
      log += key + '="' + value.toString().replace(/"/g, '') + '" ';
    }
  }
  return log;
};

编辑:

我测试了这个有效的解决方案,但我不确定我是否做得对:

export function apiLogger(level: string, log: {
  method?: any,
  url?: any,
  requestStep?: string,
  responseStatus?: any,
  responseMessage?: any,
  response?: any,
}, endPoint: string): void {

  const transportMain = new winston.transports.File({
    timestamp: () => (new Date().toLocaleTimeString()),
    datePattern: 'yyyy-MM-dd',
    level: config.application.mode === 'test' ? 'emerg' : 'info',
    filename: path.join(process.cwd(), config.application.log.dir, endPoint + '.log'),
    maxsize: 1024 * 1024 * 100, // 100MB
    colorize: false,
    prepend: true,
    json: false,
  });

  const loggerInstance = new (winston.Logger)({
    transports: [
      transportMain,
    ],
  });

  switch (level) {
    case 'info':
      loggerInstance.info(generateLog(log));
      break;
    case 'error':
      loggerInstance.error(generateLog(log));
      break;
    case 'warn':
      loggerInstance.warn(generateLog(log));
      break;
    case 'verbose':
      loggerInstance.verbose(generateLog(log));
      break;
    case 'debug':
      loggerInstance.debug(generateLog(log));
      break;
    case 'silly':
      loggerInstance.silly(generateLog(log));
      break;
    default:
      loggerInstance.info(generateLog(log));
      break;
  }
}

1 个答案:

答案 0 :(得分:2)

您可以为每个API创建一个记录器,每个记录器都有自己的文件:

const { Logger, transports } = require('winston');

const logger1 = new Logger({
  transports: [new transports.File({ filename: 'log1.log' })]
});

const logger2 = new Logger({
  transports: [new transports.File({ filename: 'log2.log' })]
});

logger1.info('log1');
logger2.info('log2');
  

修改

您每次都在创建记录器,而不是像以下那样:

const apis = ['api1', 'api2'];
const loggers = apis.reduce((memo, api) => {
  memo[api] = new Logger({
    transports: [new transports.File({ filename: `${api}.log` })]
  });
  return memo;
}, {});

const apiLogger = (level, message, api) => {
  loggers[api].log(level, message);
};

apiLogger('info', 'msg1', 'api1');
apiLogger('info', 'msg2', 'api2');