NestJS日志全局配置:如何统一启用/禁用指定级别日志
解决方案
完全可以在main.ts入口文件中完成全局日志级别统一配置,无需修改现有工具类的日志声明代码,具体实现如下:
方案1:使用Nest内置Logger全局配置(最简实现)
在初始化Nest应用时直接指定日志级别,根据环境变量判断是否为生产环境,动态调整允许输出的日志等级即可:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { LogLevel } from '@nestjs/common'; async function bootstrap() { // 按环境定义允许输出的日志级别 const isProduction = process.env.NODE_ENV === 'production'; const logLevels: LogLevel[] = isProduction ? ['warn', 'error'] // 生产环境仅保留警告、错误输出,自动屏蔽log/debug/verbose三个级别 : ['log', 'error', 'warn', 'debug', 'verbose']; // 开发环境保留全级别日志 const app = await NestFactory.create(AppModule, { logger: logLevels, }); await app.listen(3000); } bootstrap();
注意:你现有代码中直接
new Logger(A.name)创建的所有日志实例都会自动继承全局配置,无需做任何业务代码修改,生产环境下对应级别的日志输出会被自动拦截。
方案2:自定义全局Logger(扩展需求可选)
如果后续需要更复杂的日志逻辑(比如生产环境输出JSON格式、日志上报到第三方服务),可以实现自定义Logger并全局注册,同样对所有已声明的Logger实例生效:
// src/common/custom-logger.ts import { ConsoleLogger, LogLevel } from '@nestjs/common'; export class CustomLogger extends ConsoleLogger { protected logLevels: LogLevel[] = process.env.NODE_ENV === 'production' ? ['warn', 'error'] : ['log', 'error', 'warn', 'debug', 'verbose']; log(message: any, context?: string) { if (!this.isLevelEnabled('log')) return; // 可在这里扩展自定义逻辑,比如格式化输出、日志上报 super.log(message, context); } debug(message: any, context?: string) { if (!this.isLevelEnabled('debug')) return; super.debug(message, context); } verbose(message: any, context?: string) { if (!this.isLevelEnabled('verbose')) return; super.verbose(message, context); } }
在main.ts中全局注册自定义Logger:
import { CustomLogger } from './common/custom-logger'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: new CustomLogger(), }); await app.listen(3000); } bootstrap();
内容的提问来源于stack exchange,提问作者AweSIM
相关产品推荐
相关产品推荐

