diff --git a/src/server.js b/src/server.js index 12a3e1e..751320e 100644 --- a/src/server.js +++ b/src/server.js @@ -9,7 +9,9 @@ const { createServer } = require('http') const { API_URL, NODE_ENV, PORT } = require('./constant') -const server = createServer(require('.')) +const server = createServer((req, res) => + require('./util/uuid').withUUID(() => require('.')(req, res)) +) server.listen(PORT, () => { debug({ @@ -53,6 +55,7 @@ if (NODE_ENV === 'production') { process.on('uncaughtException', error => { debug.error('uncaughtException', { message: error.message || error, - requestUrl: error.response?.requestUrl + requestUrl: error.response?.requestUrl, + stack: error.stack }) }) diff --git a/src/util/uuid.js b/src/util/uuid.js new file mode 100644 index 0000000..4652092 --- /dev/null +++ b/src/util/uuid.js @@ -0,0 +1,22 @@ +'use strict' + +const { AsyncLocalStorage } = require('async_hooks') +const { randomUUID } = require('crypto') + +const asyncLocalStorage = new AsyncLocalStorage() + +const overrideWrite = stream => { + const originalWrite = stream.write + stream.write = function (data) { + originalWrite.call(stream, `${getUUID()} ${data}`) + } +} + +overrideWrite(process.stderr) +overrideWrite(process.stdout) + +const getUUID = () => asyncLocalStorage.getStore() + +const withUUID = fn => asyncLocalStorage.run(randomUUID(), fn) + +module.exports = { getUUID, withUUID }