What location is the optimal choice for documenting logs at a debugging level?

My team and I have been deeply contemplating the best location for writing a debug-level log during our development process.

We are utilizing winston in conjunction with winston-daily-rotate-file to separate out different aspects of logging, as well as nest-winston, a Nest module wrapper for winston logger.

After much consideration, we have decided to create a customizable logger service by extending the built-in Logger class.

@Injectable()
export class LoggerService extends Logger {
  constructor(
    @Inject('winston')
    private readonly logger: winston.Logger,
  ) { super(); }

 info(message: string, context?: string): void {
   this.logger.info(message, { context });
   super.log(message, context);
  }

 debug(message: string, context?: string): void {
   // To delegate the call to the parent class, no winston used.
   super.debug(message, context);
  }

 error(message: string, trace: string, context?: string): void {
   this.logger.error(message, { context });
   super.error(message, trace, context);
  }
}

One key aspect is that we have intentionally not configured the storage device (Transports) at the debug level. This ensures that logs are only printed to the console during development.

With our custom LoggerService in place, it can now be utilized anywhere within the same context. For example,

@Controller('users')
export class UsersController {
  constructor(private readonly logger: LoggerService) {}

}

@Injectable()
export class UsersService {
  constructor(private readonly logger: LoggerService) {}

  // Within a method, perform debugging logic.
  this.logger.debug(message, UsersService.name);
}

While this approach seems adequate initially, it may lead to code becoming messy if overused elsewhere.

To address this concern, we contemplated centralizing the debugging process and arrived at the idea of utilizing interceptors to handle this task.

import { LoggerService } from '../../logger/logger.service';

@Injectable()
export class DebuggingInterceptor implements NestInterceptor {
  constructor(private readonly logger: LoggerService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const ctx = `${context.getClass().name} ➜ ${context.getHandler().name}()`;

    return next
      .handle()
      .pipe(
        tap((response) => {
          if (process.env.NODE_ENV === 'development') {
            this.logger.debug(response, ctx);
          }
        }),
      );
  }
}

The act of checking the environment before printing the debug log seems clunky to me.

I have concerns that perhaps relying on the interceptor approach above might not be entirely correct?

How could I go about addressing this issue in a more efficient manner?

Answer №1

In my opinion, utilizing an interceptor is a suitable approach. If you're hesitant about checking the environment in the interceptor, you could alternatively perform this check within the LoggerService class to determine whether or not to invoke the super.debug() method. This way, you can simply use this.logger.debug(response, ctx).

On a related note, I'm currently developing my own revised version of the logger and addressing the challenges of injecting the class name into the logger for setting the context within it. However, this process is proving to be time-consuming. Just a suggestion for another potential solution.

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

Resolving conflicts between AbortSignal in node_modules/@types/node/globals.d.ts and node_modules/typescript/lib/lib.dom.d.ts within an Angular project

An issue occurred in the file node_modules/@types/node/globals.d.ts at line 72. The error message is TS2403: Subsequent variable declarations must have the same type. Variable 'AbortSignal' should be of type '{ new (): AbortSignal; prototype ...

Creating a Prisma schema with a complex nested structure and incorporating an array of strings for a specific property

I'm trying to create a detailed Prisma schema for a product database that includes nested properties and an array of strings for image content. The structure I'm aiming for looks like this: interface Product { id: number; name: string; ...

Unable to locate 'http' in error handling service for Angular 6

My current project involves creating an Error Handling Service for an Angular 6 Application using the HTTP Interceptor. The main goal of this service is to capture any HTTP errors and provide corresponding error codes. However, my lack of familiarity with ...

Error message: "Declared app-routing module in Angular 2 is encountering routing declaration

Currently, I am immersing myself in learning Angular 2 through the official tutorial available at https://angular.io/docs/ts/latest/tutorial/toh-pt5.html. However, I have encountered an issue related to routing. The error message displayed states: Type Das ...

Having trouble using the Aceternity interface as it keeps giving me a type error

I am facing an issue when trying to integrate the Acternity UI component library with nextjs. The error message I keep encountering is: "Property 'pathLengths' is missing in type '{}' but required in type '{ pathLengths: MotionValu ...

Retrieve only non-null objects using a Graphql query

I am attempting to execute a query similar to this: { people{ pet{ name } } } Here is the result I am getting: { "people": { "pet": null } }, { "people": { "pet": { name: "steve" } } } I am looking to only retrieve data fo ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

There is an issue with types in React when using TypeScript: The type '(user: User) => Element' cannot be assigned to the type '((props: User) => any) & ReactNode'

I'm encountering an error in the terminal and need some assistance. I am not well-versed in TypeScript, so any guidance to resolve this issue would be highly appreciated. https://i.stack.imgur.com/PWATV.png The Loadable component code: import { Circ ...

Unable to perform module augmentation in TypeScript

Following the guidelines provided, I successfully added proper typings to my react-i18next setup. The instructions can be found at: However, upon creating the react-i18next.d.ts file, I encountered errors concerning unexported members within the react-i18 ...

Typed NextJs navigation to a specific route

<Link href="/about"> <a>About Us</a> </Link> Is there a way to ensure type safety with NextJs links? Currently, it is challenging to restructure the Link component as it is just a string. I stumbled upon this repos ...

Utilizing a single mysql connection across client and server JavaScript files within a node.js environment

I have come across similar questions on this platform, but none exactly like mine, so I hope I am not repeating something that has already been asked before. As a newcomer to node.js & socket.io, I ask for your patience as I attempt to build a multi-c ...

The function call app.set('views', viewsPath) in EJS does not seem to be functioning as expected

Software Dependencies: "ejs": "^3.1.9", "express": "^4.18.2", The structure of my project directory is as follows: /usr/src/app/ | |- app.js |- api/routers/main.js |- website |- src/views/myView.ejs |- r ...

As I work on creating a jest snapshot test, I've encountered an issue with TypeScript error while using Redux within the component

Hi, I'm currently working on snapshot testing in Jest with TypeScript and React.js. The component is fetching state from the Redux store, so I've set up a mock store with all the initial states provided. However, the test is failing and the error ...

Is the Positioning of JS Scripts in Pug and Jade Documents Important?

Have you ever wondered why a page loads faster when certain lines are placed at the end of the tag instead of inside it? script(src="/Scripts/jquery.timeago.js") This phenomenon is often seen in code like this: //Jade file with JQuery !!! 5 html(lang=" ...

Is there a technique to block small increments in a Time Input field?

Currently in the process of developing a tool to automate task scheduling within an Angular app. I am looking for a way to restrict the user's input when selecting the hour for task execution without having to install a complex input management packag ...

Customize the border color of a dynamic textbox with Angular

I'm using Angular to create dynamic textboxes. <span *ngFor="let list of lists[0].question; let i = index"> {{ list }} <input type="text" *ngIf="i != lists[0].question.length-1" [(ngModel)] ...

What steps can be taken to fix the SequelizeDatabaseError NaN error while working with sequelize?

I am encountering an issue when running a basic sequelize.js query for my model that's causing this error. Executing (default): CREATE TABLE IF NOT EXISTS `Books` (`id` INTEGER PRIMARY KEY, `title` VARCHAR(255), `author` VARCHAR(255), `genre` VARCHAR ...

Error message: "The function app.functions is not a valid function in Angular Fire Functions

Currently, I am utilizing Angular v16 alongside Angular Fire v16 and Firebase v9. Following the instructions, I completed all the necessary setup steps including executing firebase login, firebase init, and converting the functions to typescript. Next, wi ...

Issues with routing in Node.js using Express

This is my first attempt at programming. I am currently in the process of setting up routing in the following way: var indexRouter = require('./routes/index'); var loginRouter = require('./routes/login'); app.use('/', indexRo ...

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...