You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用自定义Logger捕获NestJS Bootstrap阶段错误并写入日志文件

解决方法

1. 补全自定义Logger的Nest接口实现

你的LoggerService需要完整实现NestJS要求的LoggerService接口,补全缺失的debug、verbose方法,避免Nest内部调用这些方法时出现异常:

// logger.ts 新增两个方法
debug(message: string): void {
  const currentDate = new Date();
  this.logger.debug(message, {
    timestamp: currentDate.toISOString(),
    context: this.context,
  });
  this.formatedLog('debug', message);
}

verbose(message: string): void {
  const currentDate = new Date();
  this.logger.verbose(message, {
    timestamp: currentDate.toISOString(),
    context: this.context,
  });
  this.formatedLog('verbose', message);
}

可按需在formatedLog方法中补充对应日志级别的控制台输出样式。

2. 捕获bootstrap阶段的全局异常

修改main.ts,给bootstrap函数加try/catch逻辑,同时监听Node全局的未捕获异常和未处理的Promise拒绝,所有错误都走自定义Logger落盘:

import { ValidationPipe, Logger } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { ConfigService } from '@nestjs/config';
import { AppModule } from "./app.module";
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
import { LoggerService } from "logger";
// 提前实例化全局Logger,用来捕获bootstrap全流程的错误
const globalLogger = new LoggerService('Bootstrap');

async function bootstrap() {
  try {
    const app = await NestFactory.create(AppModule, {
      logger: globalLogger, 
      abortOnError: false
    });
    
    app.enableCors();

    await app.listen(3000);
    globalLogger.log(`Application is running on: ${await app.getUrl()}`);
  } catch (err) {
    // 捕获bootstrap阶段所有错误,写入日志文件
    globalLogger.error('Nest application bootstrap failed', (err as Error).stack);
    // 错误处理完成后可按需退出进程
    process.exit(1);
  }
}

// 监听全局未捕获的同步异常
process.on('uncaughtException', (err) => {
  globalLogger.error('Uncaught Exception', err.stack);
  process.exit(1);
});

// 监听全局未处理的异步Promise拒绝
process.on('unhandledRejection', (reason: any) => {
  globalLogger.error('Unhandled Rejection', reason?.stack || reason);
  process.exit(1);
});

bootstrap();

3. 确保日志目录存在

winston不会自动创建日志目录,启动前要确保logs目录存在,可在logger.ts中新增目录初始化逻辑:

// logger.ts 顶部引入依赖
import * as fs from 'fs';
import * as path from 'path';

// 修改configGlobal静态方法
static configGlobal(options?: LoggerOptions) {
  const logDir = path.join(process.cwd(), 'logs');
  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true });
  }
  this.loggerOptions = options; 
}

在main.ts最开头调用一次初始化方法即可:

LoggerService.configGlobal();

以上调整完成后,Nest启动阶段的模块初始化错误、数据库连接错误、运行时未捕获的业务异常都会统一写入指定的日志文件。

内容的提问来源于stack exchange,提问作者Manju S Vijaykumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:24:01