@infineit/winston-logger
v1.0.27
Published
Enterprise-level logger integration package
Downloads
28
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:
To use
@infineit/winston-logger
in your NestJS application, simply import it of yourmain.ts
file:import { NestjsLoggerServiceAdapter } from '@infineit/winston-logger';; const app = await NestFactory.create(AppModule, {bufferLogs: true }); app.useLogger(app.get(NestjsLoggerServiceAdapter));
import in app.module.ts:
import { ContextModule, LoggerModule } from '@infineit/winston-logger'; @Module({ imports: [ ContextModule, LoggerModule.forRoot(PrismaService), ] })
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 🇮🇳