提问者:小点点

在my NodeJS+React+Mongo应用中实现日志记录; 如何确保它是可伸缩的?


我有一个MERN Web应用程序,我正在实现登录。

这个应用程序还处于早期开发阶段,但我知道它将在未来的几个月和几年中扩大规模。

具体地说,

  • 应该如何构造日志架构?
  • 是否应强制执行日志类型,类别等?
  • 有没有任何NPM软件包可以让我的生活更轻松?

谢啦! :)


共1个答案

匿名用户

我应该如何构造我的日志架构?

这取决于您的需要,大多数时候,您需要将日志以特定的格式进行结构化,以便以后可以将它们转换为一些有意义的数据。 大多数情况下,您需要记录usernameiptimestamaction

是否应该强制执行日志类型,类别等?

再看情况而定,但大多数时候,是的,应该这样做。

有没有什么NPM软件包可以让我的生活更轻松?

winston是在nodejs中实现日志记录的流行选择

您可以这样做:

import winston from 'winston';
import config from '../config/config';
import {LOGGER_LEVELS} from '../utils/app.constants';
const {combine, timestamp, label, printf, errors, metadata} = winston.format;

const myFormat = printf(({level, message, label, timestamp}) => {
  return `[${level}] ${label} ${timestamp} ${message}`;
}); // any format you desire

const transports: any = [];
if (process.env.NODE_ENV !== 'development') {
  transports.push(
    new winston.transports.Console(),
    new winston.transports.File({
      filename: 'combined.log', // can save the logs to a file 
      level: LOGGER_LEVELS.INFO
    }),
    new winston.transports.File({
      filename: 'error.log',
      level: LOGGER_LEVELS.ERROR
    })
  );
} else { // for development you want the console to be printed on terminal
  transports.push(
    new winston.transports.Console({
      format: winston.format.combine(winston.format.cli(), winston.format.splat())
    })
  );
}

const LoggerInstance = winston.createLogger({
  level: config.logs.level,
  levels: winston.config.npm.levels,
  format: combine(
    label({label: 'date:'}),
    timestamp({
      format: 'MM-DD-YYYY HH:mm:ss'
    }),
    errors({stack: true}),
    myFormat
  ),
  transports
});

export default LoggerInstance;

然后,在需要使用它的任何地方,只需创建一个logger实例,就可以使用它。

LoggerInstance.log({
      level: LOGGER_LEVELS.INFO,
      message: <any_message>
    });