Created
August 25, 2018 20:02
-
-
Save hbarcelos/a276e1cad0e3813e40536627188b25ba to your computer and use it in GitHub Desktop.
Contextual Logger - CLS namespace differentiation
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
diff --git a/logger.js b/logger.js | |
index dbac73a..3aa3418 100644 | |
--- a/logger.js | |
+++ b/logger.js | |
@@ -1,9 +1,13 @@ | |
const pino = require('pino'); | |
const { createNamespace } = require('cls-hooked'); | |
+let counter = 0; | |
+ | |
function createLogger(opts, destination) { | |
const baseLogger = pino(opts, destination); | |
- const cls = createNamespace('@@logger'); | |
+ const cls = createNamespace(`@@logger-${counter}`); | |
+ | |
+ counter += 1; | |
return Object.assign(baseLogger, { cls }); | |
} |
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
diff --git a/logger.test.js b/logger.test.js | |
index 7b137e0..45c16ca 100644 | |
--- a/logger.test.js | |
+++ b/logger.test.js | |
@@ -35,3 +35,10 @@ test(`Exposes a CLS namespace`, t => { | |
t.truthy(logger.cls); | |
}); | |
+ | |
+test(`2 different loggers don't share the same namespace`, t => { | |
+ const logger = createLogger(); | |
+ const anotherLogger = createLogger(); | |
+ | |
+ t.notDeepEqual(logger.cls, anotherLogger.cls); | |
+}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment