0

I have an internal logger project.

Until now, we are managing the global parameters context of the logger with httpContext

import * as httpContext from 'express-http-context';

that httpContext basically creates a context for each HTTP request flow - and we add log parameters at the begging of the flow that will attach as parameter logs all the way.

This code is inside the internal logger project: updating the log parameters:

setLogParameters(logParams: any): void {
    if (logParams) {
      const existingParams = httpContext.get('logParams');
      logParams = { ...logParams, ...existingParams };
      httpContext.set('logParams', logParams);
    }
  }

attaching the httpContext as logParams to the actual log info that the service uses.

const addAppNameFormat = format((info) => {
  if (httpContext) {
    info = {
      ...info,
      ...httpContext.get('logParams')
    };
  }
  return info;
});

The problem with that solution - there are scenarios that don't trigger by HTTP request - for example, pulling a message from Pub Sub subscription) - in those scenarios, the HTTP Context variable is not initialized - because there is no new HTTP request.

I have tried to mimic the express-http-context behavior - https://github.com/skonves/express-http-context/blob/master/index.js and make on my own context object. On the express-http-context - I based on the express server that listen to HTTP requests - that way it really open new session for each request:

    //on my app.ts
    this.app.use(httpContext.middleware);

    //on express-http-context
    'use strict';
const cls = require('cls-hooked');

const nsid = 'a6a29a6f-6747-4b5f-b99f-07ee96e32f88';
const ns = cls.createNamespace(nsid);

/** Express.js middleware that is responsible for initializing the context for each request. */
function middleware(req, res, next) {
    ns.run(() => next());
}

How can I trigger a specific point to open a new session?

This for example doesn't work - I need to execute the middlware function - and it need to take parameter [next: NextFunction] on some way.

function handlePulledMessage(message: any, ....) {
    
    loggerContext.middleware;
    loggerContext.set('X', 100);
    loggerContext.set('Y', 200);
    loggerContext.set('Z', 300);
}

How can I do it?

  • Welcome to SO! Ask a clear question instead of saying "Hope you have some ideas for that". Also, you don't need to say thanks in your post :) See https://stackoverflow.com/help/someone-answers – rainbow.gekota Nov 30 '22 at 01:34

0 Answers0