简体   繁体   English

如何自定义 nest.js 记录器

[英]how to customize nest.js logger

I want to remove the default log format, and use only custom log message.我想删除默认日志格式,只使用自定义日志消息。 ::1 2021-08-10T10:29:52.000Z PUT / http 200 18 3000 27ms I need help creating custom logger and below is the codes I have so far. ::1 2021-08-10T10:29:52.000Z PUT / http 200 18 3000 27ms我需要帮助创建自定义记录器,以下是我到目前为止的代码。 it logs with default log format [Nest] 28869 - 2021. 08. 10 10:23:03AM LOG ${custom log message}它以默认日志格式记录[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`, ); }), ); } }

Thank you in advance!先感谢您!

You can do this by overwriting the default logger and using that logger when the app bootstrap in main.ts.您可以通过覆盖默认记录器并在应用程序在 main.ts 中引导时使用该记录器来做到这一点。

Your custom logger is something like this.您的自定义记录器是这样的。

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[]) {}
}

Then create a module and provide the customer logger to that module.然后创建一个模块并将客户记录器提供给该模块。 And make it global so you can use it anywhere on your code.并使其全球化,以便您可以在代码的任何地方使用它。

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

Register LoggerMoudle in your AppModule.在您的 AppModule 中注册 LoggerMoudle。 Add customer logger to your main.ts.将客户记录器添加到您的 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)
}

Then you can inject the customeLogger service into the Logging interceptor and your work is done.然后你可以将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