pnpm i winston logform yiu-nest-winston
WinstonModule
默认全局注入。
import { Module } from '@nestjs/common'
import { WinstonModule, WinstonModuleOptions } from 'yiu-nest-winston'
import { createLogger } from 'winston'
const options: WinstonModuleOptions = {
instance: createLogger(),
}
@Module({
imports: [
WinstonModule.forRoot(options),
],
})
export class AppModule {}
import { Module } from '@nestjs/common'
import { WinstonModule } from 'yiu-nest-winston'
@Module({
imports: [
WinstonModule.forRootAsync({ useClass: WinstonConfigService }),
],
})
export class AppModule {}
WinstonConfigService
代码如下:
import { Injectable } from '@nestjs/common'
import { transports } from 'winston'
import {
WinstonModuleOptions,
WinstonModuleOptionsFactory,
} from 'yiu-nest-winston'
@Injectable()
export class WinstonConfigService implements WinstonModuleOptionsFactory {
createWinstonModuleOptions(): WinstonModuleOptions {
return {
level: 'silly',
transports: [new transports.Console()],
}
}
}
import { Injectable } from '@nestjs/common'
import { Logger } from 'winston'
import { InjectWinston, InjectWinstonYiu, WinstonYiu } from 'yiu-nest-winston'
@Injectable()
export class AuthService {
constructor(
// 此处注入的是全局的winston单例
@InjectWinston()
private readonly winstonLogger: Logger,
// 此处注入的是当前Service的`WinstonYiu`,自动配置好了context
@InjectWinstonYiu()
private readonly yiuLogger: WinstonYiu,
) {}
}
你可以考虑从yiu-winston-kit库使用Nest
风格的printf
。