npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@team_seki/winston-logger

v0.1.0

Published

This library was generated with [Nx](https://nx.dev).

Downloads

117

Readme

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();
}