Search code examples
javascripttypescriptloggingnestjswinston

How to configure a winston service with nestjs?


I have a basic nestjs app, I'm trying to use winston as logger service... this breaks my app and I really don't know to fix/revert this. I've tried uninstalling the winston packages, rm node_modules and npm install again, nothing is working.

node -v: v11.15.
nest -v: 7.1.5
yarn -v: 1.22.4
npm -v: 6.14.5

The error I get:

[11:37:19 AM] Found 0 errors. Watching for file changes.

internal/modules/cjs/loader.js:670
    throw err;
    ^

Error: Cannot find module './app.module'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:668:15)
    at Function.Module._load (internal/modules/cjs/loader.js:591:27)
    at Module.require (internal/modules/cjs/loader.js:723:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Object.<anonymous> (/Users/dtmirror/app-api/dist/src/main.js:4:22)
    at Module._compile (internal/modules/cjs/loader.js:816:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)

package installed:

npm i winston

LoggerService:

import * as winston from 'winston';
import { LoggerOptions } from 'winston';

export class LoggerService {
    private logger;

    public static loggerOptions: LoggerOptions = {
        transports: [
            new winston.transports.File({ filename: 'app.log' })
        ]
    }

    constructor(private context: string, transport?) {
        this.logger = (winston as any).createLogger(LoggerService.loggerOptions);
    }

    log(message: string): void {
        const currentDate = new Date();
        this.logger.info(message, {
            timestamp: currentDate.toISOString(),
            context: this.context,
        })
    }
}

main.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { LoggerService } from '../logger.service'; // <-- this breaks everything

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

The moment I run yarn start:dev in this stage everything breaks...


Solution

  • Seems like a bad import for the AppModule. According to comments, logger was outside the src directory, which ends up causing the dist to take on a different shape