[英]Nest.JS LoggerService interface Implementation to use Winston logger require instantiation of implementation in consumer class
I use Nest.js and implemented LoggerService to customize logger.我使用 Nest.js 并实现了 LoggerService 来自定义记录器。 In implementation, it uses Winston logger and it work fine.在实现中,它使用 Winston 记录器并且工作正常。
import { LoggerService } from '@nestjs/common';
import * as winston from 'winston';
import { config } from '../config';
import * as path from 'path';
export class AppLogger implements LoggerService {
private logger: winston.Logger;
constructor(label?: string) {
this.initializeLogger(label);
}
initializeLogger(label?: string) {
this.logger = winston.createLogger({
level: config.logger.level,
format: winston.format.json(),
transports: [
new winston.transports.File({ dirname: path.join(__dirname, './../log/debug/'), filename: 'debug.log', level: 'debug' }),
new winston.transports.File({ dirname: path.join(__dirname, './../log/error/'), filename: 'error.log', level: 'error' }),
new winston.transports.File({ dirname: path.join(__dirname, './../log/info/'), filename: 'info.log', level: 'info' })
],
});
if (process.env.NODE_ENV !== 'production') {
this.logger.add(
new winston.transports.Console({
format: winston.format.simple(),
}),
);
}
}
error(message: string, trace: string) {
this.logger.log("error", "MyLogger error - " + message);
this.logger.error(message, trace);
}
warn(message: string) {
this.logger.log("warn", "MyLogger error - " + message);
//this.logger.warn('warn', message);
}
log(message: string) {
this.logger.log("info", "MyLogger error - " + message);
// this.logger.log('info', message);
}
Every controller, I have to import the the implemented logger and instantiate the same at the class level to call the respective log method as shown below.每个 controller,我必须导入实现的记录器并在 class 级别实例化相同的记录器,以调用相应的记录方法,如下所示。
import { Controller, Get } from '@nestjs/common';
import { config } from './../../config';
import { AppLogger } from '../app.logger'
@Controller()
export class HealthcheckController {
private start: number;
private logger: AppLogger = new AppLogger();
constructor() {
this.start = Date.now();
}
@Get('healthcheck')
async get() {
const now = Date.now();
this.logger.error("This is from Healthcheck log","");
return {
status: 'pass',
version: config.version,
details: {
uptime: `${Number((now - this.start) / 1000).toFixed(0)}`,
},
};
}
}
In the Main.ts在 Main.ts
this.app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ logger: new AppLogger('Nest') }),
);
Please advise, how to avoid instantiating the logger on all controller.请告知,如何避免在所有 controller 上实例化记录器。
What is the best approach.什么是最好的方法。
private logger: AppLogger = new AppLogger();
use Dependency injection to inject the service to your controller using the constructor.使用依赖注入将服务注入到您的 controller 使用构造函数。
export class HealthcheckController {
...
public constructor(private readonly appLogger: AppLogger) {}
and dont forget to use @Injectable() decorator in your service并且不要忘记在您的服务中使用 @Injectable() 装饰器
@Injectable()
export class AppLogger implements LoggerService {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.