jeremydaly / lambda-api

Lightweight web framework for your serverless applications
https://serverless-api.com
MIT License
1.41k stars 125 forks source link

Question: Local storage (cls-hooked) setup to log request/response data #180

Closed hemanth1226 closed 3 years ago

hemanth1226 commented 3 years ago

Hi, I am trying to replace my existing express application with lambda-api and trying to see if i can achieve all the existing functionalities. I liked it so far but facing some challenges and i am looking for some help.

I am trying to use "https://www.npmjs.com/package/cls-hooked" in my project to store request and response data and log them. But i am facing issues integrating it. Do you have any option to store the data and retrieve them in controllers or services and log the data?

Attached zip file and some of the code that i tried. Any help is appreciated. cls-hooked-lambda-api.zip

// handler.js
const api = require('lambda-api')({ version: 'v1.0', base: 'v1' })
const cls = require('cls-hooked');

api.use((req,res,next) => {
  req.key='testKey';
  clsNamespace = cls.createNamespace('app');
  clsNamespace.bind(req);
  clsNamespace.bind(res);
  clsNamespace.run(() => {
    clsNamespace.set('x-amzn-trace-id', "test");
    console.log('clsNameSpace value', clsNamespace)
    next();
  });
  next();
})

// Get

api.register(require('./routes/v1/products.js') )

module.exports.handler = async (event, context) => {
  return await api.run(event, context)
}
// products.js
cls = require('cls-hooked');

clsNamespace = cls.createNamespace('app');

module.exports = (api, opts) => {

  api.get('/posts', async (req,res) => {
    console.log(clsNamespace)
    // Send the response
    res.status(200).json({
      status: 'ok',
      version: req.hey,
      auth: req.auth,
      body: clsNamespace.get('x-amzn-trace-id'), // value printed as undefined
      query: req.query
    })
  })
};
Muthuveerappanv commented 3 years ago

@jeremydaly - Can you take a look at this? Same issue happens when trying to use https://nodejs.org/api/async_hooks.html too. Trying to persist custom variables per request in continuous-local-storage and use them as needed in logging, error handling, etc. I have used log-serializers, but there are use cases beyond that where cls-hooked or async-hooks have been very useful

Muthuveerappanv commented 3 years ago

This is resolved by using the cls-hooked:runPromise option

clsNamespace.runPromise(() => {
      clsNamespace.set("x-amzn-trace-id", "test id");
      // console.log(clsNamespace, "inside run");
      return Promise.resolve(next());
    });
hemanth1226 commented 3 years ago

Thanks Muthu. This worked.