Node.js NestJS使用默认记录器或类似winston的npm登录到文件、数据库等
使用默认记录器实现的NestJS。它将输出发送到控制台 我想知道,如何配置默认的记录器以将输出发送到文件、数据库 另外, 如果我想在NestJS中使用Winston,那么如何通过各种传输选项使用/inject/extendNode.js NestJS使用默认记录器或类似winston的npm登录到文件、数据库等,node.js,logging,nestjs,winston,Node.js,Logging,Nestjs,Winston,使用默认记录器实现的NestJS。它将输出发送到控制台 我想知道,如何配置默认的记录器以将输出发送到文件、数据库 另外, 如果我想在NestJS中使用Winston,那么如何通过各种传输选项使用/inject/extend 它不应与NestJS紧密耦合,并且始终能够用其他记录器进行替换。您不能将默认记录器配置为将输出发送到其他地方。 您需要创建自定义记录器或更好的记录器:扩展默认记录器以实现您的需要 import { Logger } from '@nestjs/common'; export
它不应与NestJS紧密耦合,并且始终能够用其他记录器进行替换。您不能将默认记录器配置为将输出发送到其他地方。
您需要创建自定义记录器或更好的记录器:扩展默认记录器以实现您的需要
import { Logger } from '@nestjs/common';
export class MyLogger extends Logger {
error(message: string, trace: string) {
// write the message to a file, send it to the database or do anything
super.error(message, trace);
}
}
阅读了解如何实现这一点
但是如果你想使用Winston,就没有必要重新发明轮子,你可以使用很棒的npm软件包
首先,您需要在app.module.ts
import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
[...]
@Module({
imports: [
TypeOrmModule.forRoot(typeOrmConfig),
WinstonModule.forRoot({
transports: [
new winston.transports.Console(),
],
}),
SearchesModule,
SuggestionsModule,
],
})
export class AppModule {}
然后,您可以在任何地方插入并使用记录器,如下所示:
import { Injectable, Inject } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Logger } from 'winston';
import { SuggestionsRepository } from './suggestions.repository';
@Injectable()
export class SuggestionsService {
constructor(
@InjectRepository(SuggestionsRepository)
private repository: SuggestionsRepository,
@Inject('winston')
private readonly logger: Logger,
) { }
getAllSuggestions = async () => {
this.logger.info('Returning suggestions...');
return await this.repository.getAll();
}
}
有关更多示例,请阅读。在Linux中,您只需通过管道将标准输出传输到一个文件: npm运行开始>app.log 在Powershell中,您可以使用Out文件 可能是这样(但不是powershell专家) npm运行开始|输出文件-filepath app.log
因此,logger LIB还支持在应用程序代码中直接处理文件输出。感谢您提供了非常清晰的答案和实现示例!非常有帮助。这很酷,但作为一种解决方案,它会使代码变得非常混乱,必须将其注入到您打算使用它的所有构造函数中——以及调用它。需要大量重构所有现有代码。如果这样做,您将如何每天轮换文件?