Setting up a winston logger in NestJS - A simple guide!

I am facing an issue with my nestjs app where I am trying to incorporate winston as a logger service. However, this implementation is causing my app to break and I am unsure how to resolve or revert this issue. I have attempted to uninstall the winston packages, delete node_modules folder, and reinstall npm packages, but none of these solutions have worked.

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

The error message I am encountering:

[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)

List of installed packages:

npm i winston

Here is the code for 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,
        })
    }
}

Snippet from 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();

Whenever I try running yarn start:dev, the entire application crashes in this state...

Answer №1

Looks like there was a faulty import in the AppModule. Comments suggest that the logger file was located outside of the src directory, leading to changes in the structure of the dist folder.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: Unable to assign value to 'googleUri' property of null. Resolving with Interface for two-way binding?

Can anyone help me figure out why I keep getting a 'set property of null' error while attempting 2way binding in my interface? Whenever I submit the form and trigger the onSave function, I encounter the error "Cannot set property 'googleUri ...

What could be causing the onclick function to not activate on the iOS safari browser?

My Shopify site works perfectly on all browsers except iOS Safari. When users try to click the "add to cart" button on this specific browser, it does not trigger the onclick function. This issue is unique to iOS Safari as the button works fine on desktop a ...

Effective ways to enable users to upload files in a React Native app

Being in the process of developing a react native app, I am faced with the challenge of allowing users to easily upload files from their mobile devices (pdf, doc, etc). Unfortunately, my search for a suitable native component has proven fruitless. Can anyo ...

Shut the offcanvas using a button

I am having trouble closing the offcanvas using the close button inside the offcanvas itself. Currently, I can only close it with the button that I used to open it. What mistake did I make? Please refer to the code snippet below. (function mainScript( ...

Renewing Firebase User Token in Angular Using HTTP Interceptor

I've encountered a puzzling issue while implementing error handling in my Angular HTTP Interceptor code. It appears that the code within my chain of ".then()" statements is being triggered out of order somehow. Here's a snippet of my code... im ...

A guide on triggering numerous alerts during validations in Javascript

My goal is to validate each form value with its own criteria and display an alert for each validation failure. While I am able to achieve this, the error messages are currently being shown on the same line, but I want them to be displayed on separate lines ...

Update the referenced lists in ng-admin

I'm currently working with ng-admin alongside a restful API, I have various referenced lists that undergo frequent updates from the server side. Is there a method to automatically refresh these referenced lists every 5 seconds using ng-admin? EDIT: ...

Is there a solution for resolving the 'cannot post error' in nodejs?

Recently started using node.js I am currently working on a nodejs-experss-mongodb project and I am in the process of implementing a subscription feature that has the following specific requirements: Request Method: POST URL: localhost:8080/api/v1/users/: ...

maintain visibility of website menu while scrolling

I am having trouble getting my drop-down menu to stay fixed at the top of the screen while scrolling down on my website. Despite several attempts, I have not been able to achieve this using the current CSS and menu setup. Can someone please assist me wit ...

Having a collection of JSON objects, I am unable to remove an element using the pop() method in JavaScript

Hello everyone, I have a collection of JSON objects that are initially set to null in the program like this: var jsonToSaveToDB = [ { ProductID: null, Quantity: null, TotalPrice: null } ]; As the pr ...

Dealing with multiple queryParams in Angular2: Best practices

Need help implementing a filtering mechanism in my new Angular2 app. Looking to filter a list of entries in an array based on around 20 properties. I've set up filters in one component and a list component as a child that is routed to. Initially, pas ...

What is the preferred convention for defining AngularJS directives as "attributes" versus "elements"?

When creating Angular directives, I've noticed that some directives could also be defined as either an HTML element or an attribute. I'm curious to know what the community convention is for choosing between the two, and the reasons behind it. Fo ...

Identifying the state of the sidebar is key

I am looking to create a script in JavaScript that can detect whether a sidebar has the class "active" or not. The sidebar is controlled by Bootstrap's toggle button, which adds the "active" class when clicked. <button type="button" id="sidebarCol ...

Adjust the template within a directive to dynamically include an additional directive

Challenge Create a custom directive that dynamically adds the ng-bind attribute, allowing for the use of ng-bind, ng-bind-html, or ng-bind-html-unsafe without needing to manually add it to the template definition throughout. Illustrative Example http://j ...

Loading complex models with Three.js

Whenever I attempt to load a significantly large file utilizing the appropriate loaders provided by the library, the tab in which my website is running crashes. Despite trying to implement the Worker class, it doesn't seem to resolve the issue. Here i ...

Executing JavaScript file using TypeScript code in Node.js

Is it possible to execute a JS file from TypeScript code in Node.js? One way to achieve this is by exposing the global scope and assigning values to it. For example: Global Scope (TypeScript): globalThis.names = ['Joe', 'Bob', 'J ...

Searching for a specific value within a list that has been fetched from a database using AngularJs can be achieved by simply clicking on the search button

Seeking assistance on a search functionality issue. I am able to filter search results from a list retrieved from the database and displayed on an HTML page, but facing difficulty in getting complete search results from the controller. When clicking the se ...

Unveiling the method to fetch the emitted value from a child component and incorporate it into the parent component's return data in Vue

How can I retrieve the title value passed by the Topbar component and incorporate it into the data() return section? I attempted to create a method to pass the value, but was unsuccessful despite being able to successfully log the value in the parent file. ...

A more efficient method for passing a function as an argument using the keyword "this"

When it comes to passing a function as an argument that uses the this keyword, is there a preferred method or correct way to do so? An example would be helpful in understanding this concept better: For instance, if I want to fade out an object and then r ...

Execute a function before the page reloads in ASP.NET with the help of JQuery

Is there a way to call a function before postback in Asp.Net using JQuery? ...