如何配置NestJS日志所使用的显示颜色?
NestJS日志颜色配置方案
默认情况下,NestJS的内置Logger没有提供官方的自定义颜色配置选项,官方文档也未提及相关配置方式,仅支持通过NO_COLOR环境变量禁用所有日志颜色。如果需要自定义日志颜色,可以通过以下两种方式实现:
自定义Logger实现
自己实现LoggerService接口(或继承内置的ConsoleLogger),借助chalk这类终端颜色库手动控制不同日志级别或内容的颜色。示例代码如下:import { Injectable, LoggerService } from '@nestjs/common'; import chalk from 'chalk'; @Injectable() export class CustomLogger implements LoggerService { log(message: string) { console.log(chalk.blue(`[LOG] ${message}`)); } error(message: string) { console.error(chalk.red(`[ERROR] ${message}`)); } warn(message: string) { console.warn(chalk.yellow(`[WARN] ${message}`)); } debug(message: string) { console.debug(chalk.gray(`[DEBUG] ${message}`)); } verbose(message: string) { console.log(chalk.magenta(`[VERBOSE] ${message}`)); } }之后在Nest应用初始化时替换默认Logger:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { CustomLogger } from './custom.logger'; async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: new CustomLogger(), }); await app.listen(3000); } bootstrap();集成第三方日志库
使用Winston、Pino等支持颜色配置的第三方日志库,这些库提供了更灵活的日志格式和颜色定制能力。以Winston为例,可通过format.colorize()配置不同日志级别对应的颜色:import { createLogger, format, transports } from 'winston'; import { WinstonModule } from 'nest-winston'; const logger = createLogger({ format: format.combine( format.colorize(), format.timestamp(), format.printf(({ timestamp, level, message }) => { return `${timestamp} [${level}]: ${message}`; }), ), transports: [new transports.Console()], }); async function bootstrap() { const app = await NestFactory.create(AppModule, { logger: WinstonModule.createLogger({ instance: logger }), }); await app.listen(3000); } bootstrap();
内容的提问来源于stack exchange,提问作者Sasha
相关产品推荐
相关产品推荐

