Skip to content

Instantly share code, notes, and snippets.

@hbarcelos

hbarcelos/app.js

Created Aug 25, 2018
Embed
What would you like to do?
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
You can’t perform that action at this time.