首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何捕获日志文件中的nestjs引导错误

如何捕获日志文件中的nestjs引导错误
EN

Stack Overflow用户
提问于 2021-09-15 10:55:59
回答 1查看 2.1K关注 0票数 0

我试图在nestjs中将所有日志(引导、应用程序错误消息、db连接错误消息)捕获到一个日志文件中。

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

logger.ts

代码语言:javascript
复制
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);
  }
}

我可以在下面的任何文件中使用上面的记录器记录应用程序错误消息(err,warn,info)

代码语言:javascript
复制
import { LoggerService } from 'logger';
private readonly logger: LoggerService = new LoggerService(RegistrationService.name);

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

我的main.ts如下所示

代码语言:javascript
复制
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。日志文件中的引导错误。它们被打印在控制台上,而不是记录文件。

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

代码语言:javascript
复制
[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.

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

EN

回答 1

Stack Overflow用户

发布于 2021-09-17 06:52:39

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

代码语言:javascript
复制
process.on('uncaughtException', err => {
  console.error('There was an uncaught error', err)
  process.exit(1) //mandatory (as per the Node.js docs)
})

或者,为了承诺,

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69191760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档