![](/img/trans.png)
[英]How to clear Stackdriver logs in Google Cloud Platform?
[英]NestJS logs not matching Google Cloud Stackdriver verbosity levels
我有一个在 Google Cloud (GCP) 中运行的 NestJS 应用程序。 从“日志资源管理器”查看 GCP 中的日志时,只有在严重性下拉列表中选择了default
值时,我才能看到我的 NestJS 应用程序的所有日志输出。 当我更改严重级别以过滤某些详细级别时,它不会将过滤器应用于 NestJS 日志输出,它仅在我选择了default
日志级别时显示日志。
例如,在我的 NestJS 应用程序中,当我执行log.debug("hello world")
时,我可以使用“默认”严重性在日志资源管理器中的日志输出中看到“DEBUG”,但是当我将严重性下拉列表从default
为debug
,我希望只看到与debug
对应的 NestJS 日志,但它不显示任何日志。 从我看到的内容来看,GCP 严重性下拉过滤器没有正确映射到 NestJS 日志。
您可以通过使用客户记录器覆盖默认记录器并重新格式化记录字符串以使 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.