NestJS集成iamolegga/nestjs-pino后,服务/控制器日志无法输出问题排查
问题原因及解决方案
核心原因
你在自定义服务中使用的是NestJS原生Logger,而非nestjs-pino提供的PinoLogger。原生Logger没有和你配置的pino日志传输系统绑定,因此输出的日志不会通过pino的终端传输规则显示。
另外,虽然你在AppModule中导入了LoggerModule,但没有在服务中正确注入PinoLogger实例,而是自行实例化原生Logger,导致日志无法被pino捕获输出。
解决方案
1. 替换自定义服务中的Logger为PinoLogger
修改document.service.ts,注入nestjs-pino的PinoLogger并设置上下文:
// document.service.ts import { Injectable } from "@nestjs/common"; import { PinoLogger } from "nestjs-pino"; @Injectable() export class DocumentService { constructor(private readonly logger: PinoLogger) { // 设置日志上下文,对应原生Logger的名称参数 this.logger.setContext(DocumentService.name); } async getDocument() { this.logger.info("This will appear in the console now!"); } }
2. 确保全局日志器使用PinoLogger
修改app.ts中的全局日志器配置,明确使用nestjs-pino的PinoLogger,而非Nest原生Logger:
// app.ts import { NestFactory } from "@nestjs/core"; import { FastifyAdapter, NestFastifyApplication } from "@nestjs/platform-fastify"; import { PinoLogger } from "nestjs-pino"; import { AppModule } from "./app.module"; import { pinoOptions } from "./app-logger"; import { LoggerErrorInterceptor } from "./logger-error.interceptor"; export async function bootstrap() { const fastifyAdapter = new FastifyAdapter({ logger: pinoOptions, trustProxy: true, }); const app = await NestFactory.create<NestFastifyApplication>( AppModule, fastifyAdapter, { bufferLogs: true } ); // 使用nestjs-pino的PinoLogger作为全局日志器 app.useLogger(app.get(PinoLogger)); app.useGlobalInterceptors(new LoggerErrorInterceptor()); await app.init(); return app; }
补充说明
启动日志和请求日志能正常显示,是因为nestjs-pino已经和Fastify适配器、请求拦截器做了集成,这些日志通过组件内部的PinoLogger实例输出。而你自定义服务中的原生Logger属于独立的日志实例,不在pino的处理链路中,所以无法显示。
内容的提问来源于stack exchange,提问作者realneo
相关产品推荐
相关产品推荐

