A Nest module wrapper for winston logger.
npm install --save nest-winston winston
Import WinstonModule
into the root AppModule
and use the forRoot()
method to configure it. This method accepts the same options object as createLogger()
function from the winston package:
import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
@Module({
imports: [
WinstonModule.forRoot({
// options
}),
],
})
export class AppModule {}
Afterward, the winston instance will be available to inject across entire project using the winston
injection token:
import { Controller, Inject } from '@nestjs/common';
import { Logger } from 'winston';
@Controller('cats')
export class CatsController {
constructor(@Inject('winston') private readonly logger: Logger) { }
}
Note that WinstonModule
is a global module, it will be available in all you feature modules.
Caveats: because the way Nest works, you can't inject dependencies exported from the root module itself (using
exports
). If you useforRootAsync()
and need to inject a service, that service must be either imported using theimports
options or exported from a global module.
Maybe you need to asynchronously pass your module options, for example when you need a configuration service. In such case, use the forRootAsync()
method, returning an options object from the useFactory
method:
import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import * as winston from 'winston';
@Module({
imports: [
WinstonModule.forRootAsync({
useFactory: () => ({
// options
}),
inject: [],
}),
],
})
export class AppModule {}
The factory might be async, can inject dependencies with inject
option and import other modules using the imports
option.
If you want to use winston logger across the whole app, including bootstrapping and error handling, use the following:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useLogger(app.get('NestWinston'));
}
bootstrap();