簡體   English   中英

NestJS 日志與 Google Cloud Stackdriver 詳細級別不匹配

[英]NestJS logs not matching Google Cloud Stackdriver verbosity levels

我有一個在 Google Cloud (GCP) 中運行的 NestJS 應用程序。 從“日志資源管理器”查看 GCP 中的日志時,只有在嚴重性下拉列表中選擇了default值時,我才能看到我的 NestJS 應用程序的所有日志輸出。 當我更改嚴重級別以過濾某些詳細級別時,它不會將過濾器應用於 NestJS 日志輸出,它僅在我選擇了default日志級別時顯示日志。

例如,在我的 NestJS 應用程序中,當我執行log.debug("hello world")時,我可以使用“默認”嚴重性在日志資源管理器中的日志輸出中看到“DEBUG”,但是當我將嚴重性下拉列表從defaultdebug ,我希望只看到與debug對應的 NestJS 日志,但它不顯示任何日志。 從我看到的內容來看,GCP 嚴重性下拉過濾器沒有正確映射到 NestJS 日志。

有沒有辦法配置 NestJS 日志以匹配 GCP 日志查看器中的 Stackdriver 詳細級別? 在此處輸入圖像描述

您可以通過使用客戶記錄器覆蓋默認記錄器並重新格式化記錄字符串以使 google 日志瀏覽器將分別識別嚴重性和消息來做到這一點。

以下是您的自定義記錄器


import { LoggerService } from "@nestjs/common";


export class CustomLogger implements LoggerService {

  log(message: any, ...optionalParams: any[]) {
    console.log(JSON.stringify({ "severity": "INFO", "message": message }));
  }

  /**
   * Write an "error" level log.
   */
  error(message: any, ...optionalParams: any[]) {
    console.log(JSON.stringify({"severity": "ERROR", "message": message }));
  }

  /**
   * Write a "warn" level log.
   */
  warn(message: any, ...optionalParams: any[]) {
    console.log(JSON.stringify({ "severity": "WARNING", "message": message }));
  }

  /**
   * Write a "debug" level log.
   */
  debug?(message: any, ...optionalParams: any[]) {
    console.log(JSON.stringify({ "severity": "DEBUG", "message": message }));
  }

  /**
   * Write a "verbose" level log.
   */
  verbose?(message: any, ...optionalParams: any[]) {
  }
}

確保對日志消息進行字符串化。 否則,google log explorer 無法分別識別日志級別和消息。

將您的自定義記錄器添加到記錄器模塊並使其全局化,以便您可以在應用程序的任何位置使用它。


import { Module, Global } from '@nestjs/common';
import { CustomLogger } from './logger.service';
import { LoggingInterceptor } from './logging.interceptor';

@Global()
@Module({
  providers: [CustomLogger, LoggingInterceptor],
  exports: [CustomLogger],
})
export class LoggerModule {
}

然后在 boostrap 應用程序時注冊 logger 模塊


import { CustomLogger } from './logger/logger.service';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    bufferLogs: true,
  });
  app.useLogger(app.get(CustomLogger));
  await app.listen(PORT)
}

制作一個日志攔截器並將您的日志服務注入其中,您就完成了。


import { CustomLogger } from './logger.service';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  constructor(private customLogger: CustomLogger) {}
  intercept(context: ExecutionContext, next) {
    const now = Date.now();
    const req = context.switchToHttp().getRequest();
    const method = req.method;
    const url = req.url;

    return next.handle().pipe(
      tap(() => {
        this.customLogger.log("logging string");
      }),
    );
  }
}

您可以根據需要自定義日志記錄字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM