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

@infineit/winston-logger

v1.0.27

Published

Enterprise-level logger integration package

Downloads

16

Readme

Introduction

@infineit/winston-logger is a lightweight project for implements a production-ready logger for Nest.js applications using Winston, Morgan and Prisma. This package simplifies the setup of logger and provides configurable options for instrumenting your application.

Features

  • Easy Integration: Quickly integrate logger with winston for distributed log.
  • Configurable: Provides options to customize logger configuration.
  • Lightweight: Minimal dependencies and overhead.

That implements a production-ready system advanced or basic Microservices or Monoliths projects applying concepts like:

  • Correlation IDs
  • Decoupled log transporters
  • Log levels
  • Logging Rules
  • Log formatters

Installation

  • You can install this package using npm:

    npm install @infineit/winston-logger

    Or using Yarn:

    yarn add @infineit/winston-logger

Prerequisites

  • NestJS
  • Winston
  • morgon
  • prisma

Getting Started

Follow these steps to set up and run logger. If all steps are followed correctly, logger should start without any issues:

  1. To use @infineit/winston-logger in your NestJS application, simply import it of your main.ts file:

        import { NestjsLoggerServiceAdapter } from '@infineit/winston-logger';;
    
        const app = await NestFactory.create(AppModule, {bufferLogs: true });
    
        app.useLogger(app.get(NestjsLoggerServiceAdapter));
  2. import in app.module.ts:

      import { ContextModule, LoggerModule } from '@infineit/winston-logger';
    
      @Module({
        imports: [
          ContextModule,
          LoggerModule.forRoot(PrismaService),
        ]
      })
  3. app.service.ts:

      import Logger, { LoggerKey } from '@infineit/winston-logger';
    
      constructor(@Inject(LoggerKey) private logger: Logger) {}
    
      this.logger.info('I am an info message!', {
            props: {
                foo: 'bar',
                baz: 'qux',
            },
        });

Reminder: Make sure prisma is initialize and winstonlog modal is running before starting your NestJS application to avoid initialization errors.

Configuration

You can configure the Logger using environment variables in your .env file:

  • NODE_ENV: development / staging / testing / production.
  • LOGGER_ORGANIZATION: The name of your organization as it will appear in log.
  • LOGGER_CONTEXT: The name of your context as it will appear in log.
  • LOGGER_APP: The name of your app as it will appear in log.
  • LOGGER_DATABASE_STORAGE: True/False. Default True for production or testing, It will store log to database.
  • LOGGER_LOG_LEVEL: Default log level warn,error,fatal for production or testing, It will log.
  • LOGGER_DURATION: True/False. Default False, It will store request duration in database.
  • LOGGER_DURATION_LOG_LEVEL: Default log level warn,error,fatal for production or testing, It will calculate duration for request.
  • LOGGER_CONSOLE_PRINT: True/False. Default False for production or testing.
  • LOGGER_LOG_IN_FILE: True/False. Default False for production or testing.
  • LOGGER_SLACK_INC_WEBHOOK_URL: Slack url, eg. https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXX/XXXXXXXXXXXXXXXXXXXXXXXX.

Project structure

Key concepts

NestJS Logger

NestJS uses a custom logger for bootstrap and internal logging. To use our logger, we need to create an adapter that implements the NestJS LoggerService interface. That is implemented in the NestjsLoggerServiceAdapter class.

We pass that adapter to the NestJS app on the main.ts file.

Correlation IDs

To manage correlation IDs, we use nestjs-cls library that implements a Local Storage. With that, we can isolate and share data on a request lifecycle.

The system reads the x-correlation-id HTTP header and stores it on the Local Storage. If the header is not present, the system generates a new UUID and stores it on the Local Storage.

Context Wrapper

To add custom data to all the logs, we use a wrapper LoggerContextWrapper.

That class is injected with a Transient scope. By that, we can get the caller class and add it to the logs.

Prisma Table

    model winstonlog {
        id_log        String   @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
        level         String   @db.VarChar(80)
        message       String   @db.Text
        context       String?  @db.VarChar(255)
        correlationId String?  @db.Uuid
        sourceClass   String?  @db.VarChar(255)
        props         Json?
        organization  String?  @db.VarChar(40)
        app           String?  @db.VarChar(40)
        durationMs    Decimal? @default(0) @db.Decimal(10, 4)
        stack         String?  @db.Text
        label         String?  @db.VarChar(40)
        timestamp     DateTime @default(now()) @db.Timestamptz(6)

        @@schema("public")
    }

Inspiration

This project is inspired by the excellent work from:

License

This project is licensed under the MIT License. See the LICENSE file for more details.

Author

Dharmesh Patel 🇮🇳