Parse and validate logs to adhere to the message and meta standards from Lad and Cabin.
npm:
npm install parse-logsThis package exports a function that accepts two arguments req which is either ctx.request from Koa or req from Express, and userFields, which is an Array of user fields to pick using parse-request's userFields option (by default it is simply [ "ip_address" ]).
You use this function to parse an inbound HTTP request body in order to return and validate a log object.
In order for this to work properly, the body must already be a parsed Object (it cannot be a String).
For example, below is an example request Object that you can pass as req to parseLogs(req):
constparseLogs=require('.');constreq={method: 'GET',query: {},headers: {'X-Request-Id': '123456','User-Agent': 'Test User Agent'},cookies: {},body: {err: {message: 'Oops',stack: '...'},message: 'Oops',meta: {level: 'error',user: {id: '123456',email: '[email protected]'}}},url: ''};console.log(parseLogs(req));Outputs to console:
{err: Error: Oops at ... (::), message: 'Oops', meta:{level: 'error', user:{id: '123456', email: '[email protected]' }, id: '636e9a831bdc98012abd4519', timestamp: '2022-11-11T18:54:59.000Z', request:{method: 'GET', headers: [Object], id: '123456' }, duration: 0.728459 } }Note that there is a user object returned, which will be parsed from req.user automatically.
The user object will also have a ip_address property added, but only if one does not already exists and if an IP address was actually detected.
Additionally, err, meta.err, and meta.original_err properties from a request body payload will be parsed into Error objects with stack traces (normalized across Node and browser environments).
For an example implementation please refer to the Forward Email codebase.
constparseLogs=require('parse-logs');constbodyParser=require('koa-bodyparser');app.use(bodyParser());app.use((ctx,next)=>{constlog=parseLogs(ctx.request);console.log(log);ctx.body=log;});constparseLogs=require('parse-logs');constbodyParser=require('body-parser');app.use(bodyParser.json());app.use(bodyParser.urlencoded());app.use((req,res,next)=>{constlog=parseLogs(req);console.log(log);res.json(log);});| Name | Website |
|---|---|
| Nick Baugh | http://niftylettuce.com/ |