@involves/logger-lib

2.2.20 • Public • Published

Logger library and middleware for Node.JS

Build status Quality Gate Status

Install

npm install @involves/logger-lib

Usage - Logger

Basic example how to log with the library:

const { logger } = require('@involves/logger-lib');

(() => {
  logger.info('Logger example')
})()

Outputs:

{"message":"Logger example","level":"info","timestamp":"2021-03-22T18:10:22.362Z"}

You can configure your logger to add more details:

const packageJson = require('./package.json')
const { LoggerConfigure, logger } = require('@involves/logger-lib');

(() => {
  LoggerConfigure({ name: packageJson.name, version: packageJson.version }, process.env.LOG_LEVEL)
  logger.info('Logger example')
})()

Outputs:

{"message":"Logger example","level":"info","program":{"name":"importer-engine-file-uploader","version":"1.0.0"},"hostname":"inv001029","timestamp":"2021-03-22T18:13:53.470Z"}

Usage - Middleware

Just add the middleware into express:

const app = require('express')()
const { LoggerMiddleware } = require('@involves/logger-lib')

app.use(LoggerMiddleware.logRequest)

Example of request log (formatted):

{
    "message": "Request log",
    "org": {},
    "req": {
        "method": "GET",
        "host": "127.0.0.1",
        "url": "/v1/healthz",
        "headers": {
            "host": "127.0.0.1:37081",
            "accept-encoding": "gzip, deflate",
            "user-agent": "node-superagent/3.8.3",
            "connection": "close"
        }
    },
    "res": {
        "status": 200,
        "headers": {},
        "elapsedTime": 55
    },
    "level": "info",
    "program": {
        "name": "importer-engine-file-uploader",
        "version": "1.0.0"
    },
    "hostname": "64ea6afaa0ff",
    "timestamp": "2021-03-22T18:16:20.231Z"
}

Usage - TraceLogger

TraceLogger was created to make distributed tracing in your microservices-based app possible. Distributed tracing is a technique that addresses logging information in microservice-based applications. A unique trace ID is passed through the call chain of each transaction in a distributed topology.

The unique trace ID is generated at the entry point of the request. The ID is then passed to each service that is used to finish the job and written as part of the services log information.

There are two ways of using TraceLogger:

  • As a middleware in your express app (TraceLogger.middleware).
  • As a callback function context (TraceLogger.consumerContext).

So, the main intention of this implementation is make possible create a traceable logs informing just once time your traceId and passing the unique id through requests or messages.

Express

Add the middleware into express and use TraceLogger.getLogger() method to use the log instance:

    const app = require('express')()
    const { TraceLogger } = require('@involves/logger-lib')

    TraceLogger.configure(PROJECT_NAME, VERSION)
    app.use(TraceLogger.middleware)
    app.get('/', function (_req, res) {
        const logger = TraceLogger.getLogger()
        logger.debug(MESSAGE)
        res.end()
    })

Service Consumers

Use the configure in the project initialization and use the consumerContext method as callback function to print the logs:

    TraceLogger.configure(PROJECT_NAME, VERSION)
    TraceLogger.consumerContext(TRACEID, () => {
        const logger = TraceLogger.getLogger()
        logger.debug(MESSAGE)
    })

Axios Interceptor

If you add the following interceptor into axios, TraceLogger will fetch traceId and whether it exists, it will add it to the request header

  axios.interceptors.request.use(TraceLogger.traceLoggerAxiosInterceptor, (error) => Promise.reject(error))

Setting and Getting traceId at execution time

It's possible change the traceId at execution time using the method TraceLogger.setTraceId(traceId):

    TraceLogger.configure(PROJECT_NAME, VERSION)
    TraceLogger.consumerContext(TRACEID, () => {
        const logger = TraceLogger.getLogger()
        TraceLogger.setTraceId(traceId)
        logger.debug(MESSAGE)
        res.end()
    })

And, it's possible get the traceId using the TraceLogger.getTraceId:

    const traceIdResult = TraceLogger.getTraceId()

Unit Tests

For unit testing use this code to mock TraceLogger:

const sandbox = require('sinon').createSandbox()
const { TraceLoggerMock, TraceLogger } = require('@involves/logger-lib')
...
TraceLoggerMock.methods(sandbox, TraceLogger)

JSON Schema

{
    "timestamp": "timestamp which the log entry was emitted, must be from UTC",
    "hostname": "name of the host which the program",
    "level": "string representation of the log level (trace|debug|info|warn|error|fatal)",
    "message": "descriptive message of the log entry",
    "traceId": "unique identifier to enable traceability",
    "org": {
        "clientId": "client unique identifier",
        "userId": "user unique identifier",
        "environmentId": "environment unique identifier",
        "applicationId": "application unique identifier"
    },
    "program": {
        "name": "name of the program",
        "version": "unique identifier of the program being executed"
    },
    "req": {
        "id": "request unique identifier",
        "method": "http method",
        "scheme": "scheme of the request",
        "host": "host of the request",
        "url": "request url with path, query and fragments",
        "headers": {
            "name of the header in lowercase": "value of the header in lowercase"
        },
        "body": "string representation of the request body",
        "ip": "IP address of the client that initiates the request"
    },
    "res": {
        "status": "http status code",
        "headers": {
            "name of the header in lowercase": "value of the header in lowercase"
        },
        "body": "string representation of the response body",
        "bodyByteLength": "byte length of the response body",
        "elapsedTime": "time duration to process the request"
    },
    "error": {
        "message": "error message",
        "stacktrace": "error stacktrace"
    }
}

logless routes

It's possible to block a certain path from being logged by using the env variable exemple: LOGLESS_ROUTES="/docs, /healthz, /home, /logs"

If not created it will block by default the following routes: DEFAULT_LOGLESS_ROUTES = ['/docs', '/healthz']

Readme

Keywords

Package Sidebar

Install

npm i @involves/logger-lib

Weekly Downloads

169

Version

2.2.20

License

ISC

Unpacked Size

40.8 kB

Total Files

20

Last publish

Collaborators

  • iotbernardes