Created
March 29, 2019 21:14
-
-
Save kjin/377847d396ef6b6beaae191da3e8fdbe to your computer and use it in GitHub Desktop.
This file contains 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 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