@team_seki/winston-logger
TypeScript icon, indicating that this package has built-in type declarations

0.1.0 • Public • Published

winston-logger

This library was generated with Nx.

Building

Run nx build winston-logger to build the library.

Running unit tests

Run nx test winston-logger to execute the unit tests via Jest.

Examples

Minimal usage of the principal class

import { WinstonLogger } from "./custom-logger";

async function main() {
  const logger = new WinstonLogger({appName: "logger-tester", environment: "development", level: "trace" });

  // Get the message format in 
  const httpReqMessage = logger.formatToHttpRequest({
    remoteHost: "127.0.0.1",
    bytesSent: 2302,
    httpStatus: 200,
    method: "GET",
    msTime: 1234,
    path: "/api/resource",
    protocolVersion: "HTTP/1.0",
    timestamp: Date.now(),
  });

  logger.trace(httpReqMessage, { some: "data" });
  logger.trace("tracing to mundo", { some: "data" });
  logger.debug("debugin to mundo", { some: "data" });
  logger.info("informing to mundo");
  logger.warn("warning to mundo", { some: "data" });
  logger.error(new Error("bad error"), { cause: "la mia" }, "BAD_ERROR");
  logger.fatal(new Error("fatal error"), { cause: "la mia" }, "FATAL_ERROR");
}

main()

Setup different transports example and output formats

const logger = new WinstonLogger({
  appName: "logger-tester",
  environment: "development",
  level: "trace",
  outputFormat: "text",
  customTransports: [new winston.transports.File({ filename: "combined.log", level: "info" })],
});

// and / or
logger.addTransport(new winston.transports.File({ filename: "combined.log", level: "info" }))

Usage in NestJS

For using the logger with NestJS you need to configure the global logger module exported in the library under the namespace NestJS in your main App Module in the first place:

import { Module } from '@nestjs/common';
import { NestJS } from '@team_seki/winston-logger';

import { AppController } from './app.controller';
import { AppService } from './app.service';

import { UsersModule } from './users/users.module';

@Module({
  imports: [
    UsersModule,
    NestJS.LoggerModule.forRoot({
      appName: process.env.PRODUCT_NAME,
      environment: process.env.NODE_ENV,
      level: process.env.PRODUCT_LOG_LEVEL ?? process.env.LOG_LEVEL,
      outputFormat: process.env.NODE_ENV == "development" ? "text" : "json",
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Later on, since the logger module is global you can include the dependency other services or controllers directly like this:

import { Injectable } from '@nestjs/common';
import { CreateParams, User, ... } from '@users/domain';
import { NestJS } from '@team_seki/winston-logger';

@Injectable()
export class UsersService {
  // Dependecies
  constructor(
    // ...
    private myLogger: NestJS.NestLogger
  ) {}

  async createNewUser(newUserDto: CreateParams) {
    const newUser = User.create(newUserDto);
    // ...

    this.myLogger.trace(`- 🚀 [UserCreated] domain event published to: ${UserCreated.USER_CREATED_TOPIC} topic`, {
      userId: newUser.id,
    });

    return newUser;
  }
}

Guides

Overriding the main app logger

If you need to configure the main logger of the Nestjs app this will use our logger for the app internal processes

import { Request, Response, NextFunction } from 'express';
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

import { AppModule } from './app/app.module';
import { NestJS } from '@team_seki/winston-logger';

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

  app.useLogger(app.get(NestJS.NestLogger));

  const port = process.env.PORT || 3000;
  await app.listen(port);
  Logger.log(`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`);
}

bootstrap();

Using cls-rtracer for tracking request ids

In order to enforce the policy of propagating request ids in every log associated with an HTTP request you could use the following approach:

// main.ts
import { Request, Response, NextFunction } from 'express';
import rTracer from 'cls-rtracer';
import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

import { AppModule } from './app/app.module';
import { NestJS } from '@team_seki/winston-logger';

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

  app.useLogger(app.get(NestJS.NestLogger));

  app.use(rTracer.expressMiddleware({ useHeader: true }));

  const port = process.env.PORT || 3000;
  await app.listen(port);
  Logger.log(`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`);
}

bootstrap();
// app.module.ts

import { Module } from '@nestjs/common';
import rTracer from 'cls-rtracer';

import { NestJS } from '@team_seki/winston-logger';

import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    NestJS.LoggerModule.forRoot({
      appName: 'logger-tester',
      environment: 'development',
      level: 'trace',
      getRequestId: () => rTracer.id() as string | undefined,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

HTTP Requests logging middleware

In here we recommend the following example of a logger express middleware for enforcing the http request format in every request issued to the server (assuming NestJs uses Expressjs underground)

import { Request, Response, NextFunction } from 'express';
import { NestJS } from '@team_seki/winston-logger';

export const loggerMiddleware = (req: Request, res: Response, next: NextFunction) => {
  const logger = app.get(NestJS.NestLogger);
  const start = Date.now();

  res.once('finish', () => {
    const bytesSent = parseInt(res.getHeaders()['content-length']?.toString() ?? '0');
    const now = Date.now();
    logger.debug(
      logger.formatToHttpRequest({
        remoteHost: req.ip ?? 'unknown',
        path: req.path,
        protocolVersion: `${req.protocol.toUpperCase()}/${req.httpVersion}`,
        bytesSent: bytesSent,
        httpStatus: res.statusCode,
        method: req.method,
        msTime: now - start,
        timestamp: now,
      })
    );
  });

  next();
}

Readme

Keywords

none

Package Sidebar

Install

npm i @team_seki/winston-logger

Weekly Downloads

23

Version

0.1.0

License

none

Unpacked Size

25.6 kB

Total Files

20

Last publish

Collaborators

  • moisesugarcia
  • kmilo8346
  • dmunozgaete