简体   繁体   English

NestJS:如何为不同环境设置全局日志级别

[英]NestJS: How to set global log level for different environments

I am using the NestJS in-built logger.我正在使用 NestJS 内置记录器。 I couldn't find an option to set the global log level.我找不到设置全局日志级别的选项。 For eg log level as 'verbose' for dev environment and log level as 'error' for prod environment.例如,对于开发环境,日志级别为“详细”,对于生产环境,日志级别为“错误”。

Also, is there an option to disable the stuff that NestJS adds in the output ie timestamp and other info and only log the message?另外,是否有一个选项可以禁用 NestJS 在输出中添加的内容,即时间戳和其他信息,并且只记录消息? I need this as we use Kibana logs and it automatically adds the required fields.我需要这个,因为我们使用 Kibana 日志,它会自动添加必填字段。

You can set up log levels in your main.ts file:您可以在main.ts文件中设置日志级别:

const app = await NestFactory.create(AppModule, {
  logger: process.env.NODE_ENV === 'development' ? ['log', 'debug', 'error', 'verbose', 'warn'] : ['error', 'warn'],
});

You can write your own Logger with that logic and use it as a service or you can set it globally您可以使用该逻辑编写自己的 Logger 并将其用作服务,也可以全局设置

export class MyLogger extends Logger {
  error(message: string, trace: string) {
    // add your tailored logic here
    super.error(message, trace);
  }
}

const app = await NestFactory.create(ApplicationModule, {
  logger: new MyLogger(),
});

I looked for a log level switcher me too, but I didn't found.我也找了一个日志级别切换器,但我没有找到。

As proposed in the previous comment, you can create a custom logger and apply it globally to ApplicationModule .正如之前的评论中所建议的,您可以创建一个自定义记录器并将其全局ApplicationModuleApplicationModule

This custom logger will be invoked either by Nest and by you in your controller/service/etc.这个自定义记录器将由 Nest 和您在控制器/服务/等中调用。

            NestJs
                    \
                      use -> CustomLogger 
                    /
Your business logic

In your CustomLogger call either super.logger (nestjs built-in logger) and also the winston logger .在您的 CustomLogger 中调用 super.logger (nestjs 内置记录器)和winston logger

Winston Logger can be set up with transporter for kibana and accept a log level. Winston Logger 可以为 kibana 设置传输器并接受日志级别。

const winstonLogger = new winston.Logger({
                 level: LOG_LEVEL,
                 transports: [
                    <here enable trasport for logstash/kibana>
                  }),
                ],
                ...
               });

export class CustomLogger extends Logger {

  debug(message: string) {
    super.error(message, trace);
    winstonLogger.error(message)
  }

  ... (the same for warn, error, etc)
}

Finally register the CustomLogger最后注册 CustomLogger

 const app = await NestFactory.create(ApplicationModule, {
  logger: new CustomLogger(),
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM