1.0.15 • Published 28 days ago

@gromo-fintech/log4g v1.0.15

Weekly downloads
-
License
ISC
Repository
-
Last release
28 days ago

@gromo-fintech/log4g

gromo-log4g-js is a versatile and easy-to-use logging framework for JavaScript and Nest.js applications. It provides powerful logging capabilities to help developers track and debug their applications efficiently.

Features

  • Customizable Logging Levels: Configure different log levels (e.g., DEBUG, INFO, WARN, ERROR) according to your application's needs.

  • Log Formats: Choose between formatting logs a text or json

  • Log Meta Data: Logs have meta data useful for debugging like: methodName, lineNumer, className, filePath, timestamp etc.

  • Saves Logs as stdout or files: Saves logs as stdout / stderr or save as file depending upon config. When storing logs in a file you can choose between storing in a single file, or bifurcated based on log levels. All logs files are stored at ~/.gromo-logger/<project-name>/.

  • Plug and Play Access Logs: store logs of every API request that reaches your micro-service. Track host-ip, requester ip, response time of each API alongside trace-id as part of access logs

Installation

You can install log4g.js via npm:

npm install @gromo-fintech/log4g

Usage

Basic Usage

// import logger
import { logger, LogLevel, LogFormat } from '@gromo-fintech/log4g';

// configure logger [example config]
logger.setConfig({
    enableStdout: true, // if true, prints logs on stdout and stderr
    nameOfProject: "gromoinsure-insurance", // name of your project. Used to creating log files.
    fileOptions: {
      enableFile: true, // if true, write logs to a file
      logLevel: LogLevel.INFO,// define log level to track for files
      datePattern: "DD-MM-YYYY",
      zippedArchive: false, // if true, log files are archived
      maxSize: "10k", // max size of a log file. Set to 10 KB here. 
      maxDuration: "7d", // max duration after which log rotation starts. Set to 7 days here.
    },
    logLevel: LogLevel.INFO,
    logFormat: LogFormat.TEXT,// Choose between TEXT and JSON to format logs accordingly
    transporterType: TransporterType.SINGLE_FILE, // Choose between SINGLE_FILE and BIFIRUCATED_BY_LOG_LEVEL
    overrideConsole: true, // if true, it overrides existing `console.log` in your project to log4g's implementation
    enableAccessLog?: true, // if true, stores access logs using interceptor / middleware (needs to be attached)
})

Configuration

gromo-log4g.js can configured to your needs.

keyvaluesexamplewhat it does
enableStdouttrue / falsetrueif true, prints logs on stdout and stderr
nameOfProjectany string"testingProject"name of your project. Used to creating log files.
fileOptions .enableFiletrue / falsetrueif true, write logs to a file
fileOptions.logLevelinfo / debug / warn / error (use enum)LogLevel.DEBUGdefine log level to track for files
fileOptions.datePatternstring like "YYYY-MM-DD" or "DD-MM-YYYY""DD-MM-YYYY"define date pattern to follow for logs
fileOptions.zippedArchivetrue / falsetrueif true, log files are archived
fileOptions.maxSizesize as string alongside unit."10k"max size of a log file. Set to 10 KB here.
fileOptions.maxDurationmax duration after which log rotation starts."7d"max duration after which log rotation starts. Set to 7 days here.
logLevelinfo / debug / warn / error (use enum)Overall log level (for stdout), depends
logFormat'text' / 'json' (use enum)LogFormat.TEXTDefines how logs are printed, Choose between TEXT or JSON
transporterType'single_file' / 'bifurcated_by_log_level'TransporterType.SINGLE_FILEDefines how logs files are structured.Choose between SINGLE_FILE and BIFIRUCATED_BY_LOG_LEVEL SINGLE_FILE -> All application logs are dumped into a single file. BIFIRUCATED_BY_LOG_LEVEL -> Separate log file is created for each log level.
overrideConsoletrue / falsetrueif true, it overrides existing console.log in your project to log4g's implementation
enableAccessLogtrue / falsetrueif true, stores access logs using interceptor / middleware (needs to be attached)

Attaching middleware / interceptor for access logging

In order to store access logs and extract request scope information like trace-id, host-ip, requester-ip etc you need to attach a middleware / interceptor provided by this library to your project.

For Nest.js projects

For projects implemented using nest.js framework you can use the LoggerInterceptorNest class and provide it in the provider in app.module.ts with the APP_INTERCEPTOR under provide and LoggerInterceptorNest under useClass as shown below:

import { LoggerInterceptorNest } from '@gromo-fintech/log4g';
import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
  imports: [],
  controllers: [AppController],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggerInterceptorNest
    },
    AppService
  ],
})
export class AppModule {}

or you can have it for specific controllers with:

@UseInterceptors(LoggerInterceptorNest)

For Express.js projects

For projects implemented in javascript with express.js as their core server engine you can use the provided requestMiddleware function and use as middleware:

const { logger, LogFormat, LogLevel, TransporterType, ExpressMiddleware } = require("@gromo-fintech/log4g");
const loggerOptions = {
  enableStdout: true ,
  nameOfProject : "payoutgrid",
  fileOptions: {
      enableFile: true,
      logLevel : LogLevel.INFO,
      datePattern: 'DD-MM-YYYY',
      zippedArchive: false,
      maxSize: '10k', 
      maxDuration: '1d',
  },
  logLevel : LogLevel.INFO,
  logFormat : LogFormat.JSON,
  transporterType : TransporterType.BIFIRUCATED_BY_LOG_LEVEL,
  overrideConsole : true,
  enableAccessLog : true,
};
logger.setConfig(loggerOptions);
const loggingMiddleware = new ExpressMiddleware();
app.use(loggingMiddleware.requestMiddleware);

Remember to do this before initializing all routes.

For Fastify projects

For projects implemented in javascript with fastify as their core server engine you can use the provided requestMiddleware, responseMiddleware, and errorMiddleware hooks:

const { logger, LogFormat, LogLevel, TransporterType, FastifyMiddleware } = require('@gromo-fintech/log4g');
const loggerOptions = {
  enableStdout: true,
  nameOfProject : "gromoinsure-insurance",
  fileOptions: {
      enableFile: true,
      logLevel : LogLevel.INFO,
      datePattern: 'DD-MM-YYYY',
      zippedArchive: false,
      maxSize: '10k', 
      maxDuration: '1d',
  },
  logLevel : LogLevel.INFO,
  logFormat : LogFormat.JSON,
  transporterType : TransporterType.BIFIRUCATED_BY_LOG_LEVEL,
  overrideConsole : true,
  enableAccessLog : true,
};
logger.setConfig(loggerOptions);

const fastifyMiddleware = new FastifyMiddleware();
fastify.addHook('preHandler', fastifyMiddleware.requestMiddleware);
fastify.addHook('onResponse', fastifyMiddleware.responseMiddleware);
fastify.addHook('onError', fastifyMiddleware.errorMiddleware);

The above changes will enable access logs under ~/.gromo-logger/<project-name>/access_logs and add trace id, requester-ip, URI path, API method, API response status code, and host-ips to application logs as well.

Authors

Rohan Nagariya

Intern - SDE

Rohan Nagariya is an intern at GroMo who has come from DTU and has written majority of the code for this package.

  • Email: rohan.nagariya@gromo.in

Paramdeep Singh Obheroi

Senior Software Engineer

Paramdeep is a Senior Engineer at GroMo. He has designed and reviewed the package alongside mentoring Rohan in building this package.

  • Email: paramdeep.obheroi@gromo.in

Sahej Aggarwal

Engineering Manager

Sahej is the Engineering Manager at GroMo who has initiated the project.

  • Email: sahej.aggarwarl@gromo.in
1.0.15

28 days ago

1.0.14

1 month ago

1.0.13

1 month ago

1.0.12

1 month ago

1.0.11

1 month ago

1.0.9

1 month ago

1.0.10

1 month ago

1.0.8

2 months ago

1.0.7

2 months ago

1.0.6

2 months ago

1.0.5

2 months ago

1.0.2

2 months ago

1.0.1

2 months ago

1.0.0

2 months ago

1.0.4

2 months ago

1.0.3

2 months ago

0.0.1

2 months ago