Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Winston Logger in NestJS separate module that doesn't use Classes

Tags:

winston

nestjs

I've tried a few different ways of doing this.

I can't set Winston as the default logger for NestJS at the moment because it complains about "getTimestamp" function not being in the instance.

So - for controllers in NestJS - I have used dependency injection - which works fine for the api ( REST endpoints ).

The problem is that I have moved away from OOP - so all of my libraries are written in typescript as functions. Not pure functions but better than an OOP approach ( many less bugs! )

My question is - how do I get access to the main winston logger within my libraries that don't have classes.

I am using the library nest-winston.

like image 407
Martin Thompson Avatar asked Dec 06 '25 06:12

Martin Thompson


1 Answers

Have you tried this?

create the logger outside of the application lifecycle, using the createLogger function, and pass it to NestFactory.create (nest-winston docs)

You can have a separate file that creates the logging instance, then import that into your modules/libraries as well as import it into your main.ts

// src/logger/index.ts
import { WinstonModule } from 'nest-winston';

export const myLogger = WinstonModule.createLogger({
  // options (same as WinstonModule.forRoot() options)
})
// src/myLib/index.ts
import { myLogger } from '@/logger' // I like using aliases

export const myLib = () => {
  // ...
  myLogger.log('Yay')
}
// src/main.ts
import { myLogger } from '@/logger' 
async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: myLogger
  });
}
bootstrap();
like image 200
Kieran101 Avatar answered Dec 09 '25 16:12

Kieran101



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!