Skip to content

Instantly share code, notes, and snippets.

@hbarcelos
Created August 25, 2018 22:37
Show Gist options
  • Save hbarcelos/3a2c5ff5c3ddbef84f56a9febb4ccdb6 to your computer and use it in GitHub Desktop.
Save hbarcelos/3a2c5ff5c3ddbef84f56a9febb4ccdb6 to your computer and use it in GitHub Desktop.
Contextual Logger - Example Integration
const express = require('express');
const cuid = require('cuid');
const createLogger = require('./logger.js');
const PORT = Number(process.env.PORT) || 8080;
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();
})
}
}
const app = express();
const logger = createLogger({ level: 'trace' });
app.use(clsRequestId(logger.cls, cuid));
app.get('/', async (req, res) => {
const result = await handler();
return res.json(result);
})
app.listen(PORT, () => {
logger.info(
{ endpoint: `http://localhost:${POINT}` },
'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