一、前言
最近浅浅的研究了一下nestjs这个框架,对于用惯了koa2的我来说,真的不习惯,一点都不随便,下面来说说使用nestjs怎么接入log4js替换掉它默认的日志打印工具哈!
二、安装
npm i log4js
三、代码部分
1.配置文件:common/logger/config.ts
//log4js的配置文件,我这里简单的配置一下作为演示
export function LogConfig () {
return {
"appenders": {
"console": {
"type": "console"
},
"file": { //保存日志的文件配置,支持layout自定义配置,具体去看log4js
"type": "file",
"filename": "logs/info_file.log",
}
},
"categories": {
"default": {
"appenders": ["console", "file"],
"level": "debug"
}
}
}
}
2.主要文件:common/logger/index.ts
// log4js.service.ts
import { Injectable,LoggerService } from '@nestjs/common';
import * as log4js from 'log4js';
import { LogConfig } from "./config"; //导入配置文件
//实现LoggerService类型,这个nestjs官网有大致的自定义简介
@Injectable()
export class loggerServer implements LoggerService {
private readonly logger: log4js.Logger;
constructor() {
log4js.configure(LogConfig());
this.logger = log4js.getLogger();
}
log(message: any, ...args: any[]): any {
this.logger.log(message, ...args);
}
debug(message: string, ...args: any[]): void {
this.logger.debug(message, ...args);
}
info(message: string, ...args: any[]): void {
this.logger.info(message, ...args);
}
warn(message: string, ...args: any[]): void {
this.logger.warn(message, ...args);
}
error(message: string, ...args: any[]): void {
this.logger.error(message, ...args);
}
}
3.main.ts文件
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { loggerServer } from './common/logger/index';
async function bootstrap() {
const app = await NestFactory.create(AppModule,{
cors:true,
bufferLogs: true, //这个是一定要加的,官方文档上也有介绍
});
app.useLogger(new loggerServer())
app.setGlobalPrefix('api');
await app.listen(3060);
}
bootstrap();
四、效果演示
1.项目启动之后,查看logs/info_file.log文件
2.模块使用
A.app.module.ts文件
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MongooseModule } from '@nestjs/mongoose';
import { UserModule } from './user/user.module';
import { loggerServer } from "./common/logger/index";
@Module({
imports: [
MongooseModule.forRoot(
"mongodb://127.0.0.1:22908/cornucopia",
),
UserModule
],
controllers: [AppController],
providers: [AppService,loggerServer], //注入
})
export class AppModule {}
B.app.controller.ts
import { Controller, Get } from "@nestjs/common";
import { AppService } from './app.service';
import { loggerServer } from "./common/logger";
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
private readonly logger:loggerServer,
) {}
@Get()
getHello(): string {
this.logger.error('数据不存在!') //使用
return this.appService.getHello();
}
}
五、总结
上边就是我理解的最基本的log4js使用流程,可能是我用习惯了koa2,上手这个难度真的很高,理解的也不够深刻,只能说先凑合着会用就行,后边在慢慢理解吧,希望对你有帮助,加油!