Last active
August 8, 2018 20:22
-
-
Save hbarcelos/bf4c87d7ce3034a568323d1f1f90cf0a to your computer and use it in GitHub Desktop.
Logging with CLS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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