Skip to content

Instantly share code, notes, and snippets.

@hbarcelos
Last active August 8, 2018 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hbarcelos/bf4c87d7ce3034a568323d1f1f90cf0a to your computer and use it in GitHub Desktop.
Save hbarcelos/bf4c87d7ce3034a568323d1f1f90cf0a to your computer and use it in GitHub Desktop.
Logging with CLS
const express = require('express');
const pino = require('pino');
const cuid = require('cuid');
const { createNamespace, getNamespace } = require('cls-hooked');
const logger = pino();
const loggerNamespace = createNamespace('logger');
const app = express();
function clsRequestId(namespace, generateId) {
return (req, res, next) => {
const requestId = req.get('X-Request-Id') || generateId();
res.set('X-Request-Id', requestId);
namespace.run(() => {
namespace.set('requestId', requestId);
next();
})
}
}
app.use(clsRequestId(loggerNamespace, cuid));
app.get('/', async (req, res) => {
const result = await handler();
return res.json(result);
})
app.listen(4004, () => {
logger.info(
{ endpoint: `http://localhost:4000` },
'App is running!'
)
})
function delay(timeoutMs) {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, timeoutMs);
})
}
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
async function handler() {
const namespace = getNamespace('logger');
logger.info({ requestId: namespace.get('requestId') }, 'Before')
await delay(randomInteger(1000, 10000));
logger.info({ requestId: namespace.get('requestId') }, 'Middle')
await delay(randomInteger(1000, 10000));
logger.info({ requestId: namespace.get('requestId') }, 'After')
return {};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment