This repository has been archived by the owner on Oct 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #58 from BonnierNews/feature/correlation-id-magic
Handle correlation IDs automagically
- Loading branch information
Showing
5 changed files
with
103 additions
and
5 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
"use strict"; | ||
|
||
const { AsyncLocalStorage } = require("node:async_hooks"); | ||
|
||
const debugMetaStorage = new AsyncLocalStorage(); | ||
|
||
/** | ||
* Generate an Express middleware that will add data from the request to be logged | ||
* @param {(req) => object} getDebugMetaFromReq A function that takes the | ||
* request and response objects and returns an object to be added to the debug meta | ||
*/ | ||
function initDebugMetaMiddleware(getDebugMetaFromReq) { | ||
return (req, res, next) => { | ||
const debugMeta = getDebugMetaFromReq(req); | ||
debugMetaStorage.run(debugMeta, () => { | ||
next(); | ||
}); | ||
}; | ||
} | ||
|
||
function debugMetaFormat(info) { | ||
const debugMeta = { ...getDebugMeta(), ...info.metaData?.meta }; | ||
if (Object.keys(debugMeta).length === 0) return info; | ||
return { | ||
...info, | ||
metaData: { meta: { ...getDebugMeta(), ...info.metaData?.meta } }, | ||
}; | ||
} | ||
|
||
function getDebugMeta() { | ||
return debugMetaStorage.getStore() || {}; | ||
} | ||
|
||
module.exports = { | ||
initDebugMetaMiddleware, | ||
debugMetaFormat, | ||
getDebugMeta, | ||
}; |
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
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