如何使用nestjs记录服务 [英] How to use nestjs Logging service

查看:793
本文介绍了如何使用nestjs记录服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用nestjs的内部 Logger (在 https://docs.nestjs.com/techniques/logger - >但没有说明如何使用它)

I tried to use the internal Logger of nestjs (described on https://docs.nestjs.com/techniques/logger -> but with no description of how to use it)

但我有问题(尝试注入 LoggerService 等等)

But I had problems (tried to inject LoggerService and so on)

任何人都可以解释如何做到这一点吗?

Can anybody explain how to do this?

TIA

推荐答案

最佳实践



比访问 Logger 静态地为你的类创建一个实例:

Best practise

Better than accessing the Logger statically is to create an instance for your class:

@Controller()
export class AppController {
  private readonly logger = new Logger(AppController.name);

  @Get()
  async get() {
    this.logger.log('Getting stuff');
  }
}






为什么这样更好?



1)你可以在构造函数中提供一个上下文,比如 new Logger(AppController.name)以便类名(或其他任何内容)将成为此类中所有日志消息的一部分。


Why is this better?

1) You can provide a context in the constructor like new Logger(AppController.name) so that the class name (or anything else) will be part of all log messages in this class.

2)如果您在某个时候想要扩展或替换默认 LoggerService ,除了设置新的记录器之外,您不需要更改任何应用程序代码。您的新记录器将自动使用。如果你静态访问它,它将继续采用默认实现。

2) If you at some point want to extend or replace the default LoggerService, you do not need to change any of your application code besides setting the new logger. Your new logger will automatically be used. If you access it statically it will continue to take the default implementation.

const app = await NestFactory.create(AppModule, {logger: new MyLogger()});

这篇关于如何使用nestjs记录服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆