Skip to content

Instantly share code, notes, and snippets.

@kjin
Created March 29, 2019 21:14
Show Gist options
  • Save kjin/377847d396ef6b6beaae191da3e8fdbe to your computer and use it in GitHub Desktop.
Save kjin/377847d396ef6b6beaae191da3e8fdbe to your computer and use it in GitHub Desktop.
const ah = require('async_hooks');
const express = require('express');
const { createLogger } = require('winston');
const TransportStream = require('winston-transport');
// Activate async hooks.
let requestIdHighWater = 0;
const requestIdTable = {};
ah.createHook({
init: (child, resource, parent) => {
requestIdTable[child] = requestIdTable[parent];
}
}).enable();
// OUR CODE
class MyTransport extends TransportStream {
log(info, next) {
// From the transport, the request ID is not reliable.
const actualRequestId = requestIdTable[ah.executionAsyncId()];
console.log(`Expected: ${info.expectedRequestId}, Actual: ${actualRequestId}`);
setImmediate(next);
}
}
// OUR USER'S CODE
const logger = createLogger({
defaultMeta: {
expectedRequestId: () => {
// Store a request ID.
const requestId = requestIdHighWater++;
requestIdTable[ah.executionAsyncId()] = requestId;
return requestId;
}
},
transports: [new MyTransport()]
});
const app = express();
app.get('/', async (req, res) => {
logger.info('hello');
res.sendStatus(200);
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment