【问题标题】:how to capture nestjs bootstrap errors in a log file如何在日志文件中捕获nestjs引导错误
【发布时间】:2021-11-10 11:06:24
【问题描述】:

我正在尝试将所有日志(引导、应用程序错误消息、数据库连接错误消息)捕获到 nestjs 中的单个日志文件中。

到目前为止,我正在使用自定义记录器。下面是我的自定义记录器代码

logger.ts

import * as winston from 'winston';
import * as chalk from 'chalk';
import PrettyError from 'pretty-error';
import { LoggerOptions } from 'winston';

export class LoggerService {
  private readonly logger: winston.Logger;
  private readonly prettyError = new PrettyError();
  public static loggerOptions: LoggerOptions = {
    transports: [
      new winston.transports.File({
        filename: 'logs/mgmtserver-main.log',
        format: winston.format.json()
      }),
    ],
  };
  constructor(private context: string, transport?) {
    this.logger = (winston as any).createLogger(LoggerService.loggerOptions);
    this.prettyError.skipNodeFiles();
    this.prettyError.skipPackage('express', '@nestjs/common', '@nestjs/core');
  }
  get Logger(): winston.Logger {
    return this.logger;
  }
  static configGlobal(options?: LoggerOptions) {
    this.loggerOptions = options; 
  }
  log(message: string): void {
    const currentDate = new Date();
    this.logger.info(message, {
      timestamp: currentDate.toISOString(),
      context: this.context,
    });
    this.formatedLog('info', message);
  }
  error(message: string, trace?: any): void {
    const currentDate = new Date();
    this.logger.error(`${message} -> (${trace || 'trace not provided !'})`, {
      timestamp: currentDate.toISOString(),
      context: this.context,
    });
    this.formatedLog('error', message, trace);
  }
  warn(message: string): void {
    const currentDate = new Date();
    this.logger.warn(message, {
      timestamp: currentDate.toISOString(),
      context: this.context,
    });
    this.formatedLog('warn', message);
  }
  overrideOptions(options: LoggerOptions) {
    this.logger.configure(options);
  }
  
  // this method just for printing a cool log in your terminal , using chalk
  private formatedLog(level: string, message: string, error?): void {
    let result = '';
    const color = chalk.default;
    const currentDate = new Date();
    const time = `${currentDate.getHours()}:${currentDate.getMinutes()}:${currentDate.getSeconds()}`;

    switch (level) {
      case 'info':
        result = `[${color.blue('INFO')}] ${color.dim.yellow.bold.underline(time)} [${color.green(
          this.context,
        )}] ${message}`;
        break;
      case 'error':
        result = `[${color.red('ERR')}] ${color.dim.yellow.bold.underline(time)} [${color.green(
          this.context,
        )}] ${message}`;
        break;
      case 'warn':
        result = `[${color.yellow('WARN')}] ${color.dim.yellow.bold.underline(time)} [${color.green(
          this.context,
        )}] ${message}`;
        break;
      default:
        break;
    }
    console.log(result);
  }
}

我可以在任何文件中使用上述记录器记录应用程序错误消息(错误、警告、信息),如下所示

import { LoggerService } from 'logger';
private readonly logger: LoggerService = new LoggerService(RegistrationService.name);

this.logger.warn('this is a warn message');

我的 main.ts 如下所示

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";

async function bootstrap() {

  const app = await NestFactory.create(AppModule, {
    logger: new LoggerService('Main'), abortOnError: false
  });
  
  app.enableCors();

  await app.listen(3000);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();

问题是我无法捕获 Nestfactory.create。日志文件中的引导错误。它们会打印在控制台上,但不会打印到日志文件中。

例如,以下引导错误会打印在控制台上,但不会打印到日志文件中。

[INFO] 15:12:50 [Main] Starting Nest application...
[ERR] 15:12:50 [Main] Nest cannot create the AuthorisationModule instance.
The module at index [3] of the AuthorisationModule "imports" array is undefined.

Potential causes:
- A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency
- The module at index [3] is of type "undefined". Check your import statements and the type of the module.

请帮助我。非常感谢您的帮助。

【问题讨论】:

    标签: node.js typescript logging nestjs winston


    【解决方案1】:

    这是因为在 Nest 完成初始化 App 上下文之前,您的 logger 模块不会被初始化。您的记录器将在您的应用程序运行之后而不是之前捕获所有错误。 但是,您可以利用节点的内置事件来记录/归档这些异常

    process.on('uncaughtException', err => {
      console.error('There was an uncaught error', err)
      process.exit(1) //mandatory (as per the Node.js docs)
    })
    

    或者,对于 Promise,

    process.on('unhandledRejection', err => {
      console.error('There was an uncaught error', err)
      process.exit(1) //mandatory (as per the Node.js docs)
    })
    

    https://nodejs.dev/learn/error-handling-in-nodejs#catching-uncaught-exceptions

    【讨论】:

    • 是的,你是对的。但我想将任何错误/异常捕获到日志文件中,而不是控制台中。有办法吗?
    猜你喜欢
    • 2021-06-08
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-16
    • 2020-07-22
    • 2017-01-26
    • 1970-01-01
    相关资源
    最近更新 更多