繁体   English   中英

如何自定义 nest.js 记录器

[英]how to customize nest.js logger

我想删除默认日志格式,只使用自定义日志消息。 ::1 2021-08-10T10:29:52.000Z PUT / http 200 18 3000 27ms我需要帮助创建自定义记录器,以下是我到目前为止的代码。 它以默认日志格式记录[Nest] 28869 - 2021. 08. 10 10:23:03AM LOG ${custom log message}

 @Injectable() export class LoggingInterceptor implements NestInterceptor { 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(() => { const res = context.switchToHttp().getResponse(); const delay = Date.now() - now; Logger.log( `${req.ip} ${new Date()} ${method} ${url} ${req.protocol} ${res.statusCode} ${ req.headers['content-length'] || '0' } ${req.headers.host.split(':')[1]} ${delay}ms`, ); }), ); } }

先感谢您!

您可以通过覆盖默认记录器并在应用程序在 main.ts 中引导时使用该记录器来做到这一点。

您的自定义记录器是这样的。

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

export class CustomLogger implements LoggerService {
  /**
   * Write a 'log' level log.
   */
  log(message: any, ...optionalParams: any[]) {
     console.log(message);
  }

  /**
   * Write an 'error' level log.
   */
  error(message: any, ...optionalParams: any[]) {}

  /**
   * Write a 'warn' level log.
   */
  warn(message: any, ...optionalParams: any[]) {}

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

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

然后创建一个模块并将客户记录器提供给该模块。 并使其全球化,以便您可以在代码的任何地方使用它。

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 {
}

在您的 AppModule 中注册 LoggerMoudle。 将客户记录器添加到您的 main.ts。


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)
}

然后你可以将customeLogger服务注入到Logging拦截器中,你的工作就完成了。

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(() => {
        const res = context.switchToHttp().getResponse();
        const delay = Date.now() - now;
        this.customLogger.log(
          `${req.ip} ${new Date()} ${method} ${url} ${req.protocol} ${res.statusCode} ${
            req.headers['content-length'] || '0'
          } ${req.headers.host.split(':')[1]} ${delay}ms`,
        );
      }),
    );
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM