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

@involves/logger-lib

v2.2.20

Published

Logger and middleware for http requests

Downloads

48

Readme

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']