support AsyncLocalStorage stored object merged into logs, breaking changes to constru...
[squeep-logger-json-console] / lib / logger.js
1 'use strict';
2
3 const jsonReplacers = require('./json-replacers');
4 const dataSanitizers = require('./data-sanitizers');
5
6 const nop = () => { /**/ };
7
8 class Logger {
9 /**
10 * @typedef {Object} ConsoleLike
11 * @property {Function(...):void} error
12 * @property {Function(...):void} warn
13 * @property {Function(...):void} info
14 * @property {Function(...):void} log
15 * @property {Function(...):void} debug
16 */
17 /**
18 * @typedef {Object} LoggerOptions
19 * @property {String} ignoreBelowLevel - minimum level to log, e.g. 'info'
20 */
21 /**
22 * Wrap backend calls with payload normalization and metadata.
23 * @param {LoggerOptions} options
24 * @param {Object} commonObject - object to be merged into logged json
25 * @param {AsyncLocalStorage} asyncLocalStorage - async storage for an object to be merged into logged json
26 * @param {ConsoleLike} backend - default is console
27 */
28 constructor(options, commonObject, asyncLocalStorage, backend) {
29 const logLevels = Object.keys(Logger.nullLogger);
30 const ignoreBelowLevel = options?.ignoreBelowLevel || 'debug';
31 this.backend = backend || console;
32 this.commonObject = commonObject || {};
33 this.jsonReplacers = Object.values(jsonReplacers);
34 this.dataSanitizers = Object.values(dataSanitizers);
35
36 if (asyncLocalStorage) {
37 // Override the class getter.
38 Object.defineProperty(this, 'asyncLogObject', {
39 enumerable: true,
40 get: asyncLocalStorage.getStore.bind(asyncLocalStorage),
41 });
42 }
43
44 if (!logLevels.includes(ignoreBelowLevel)) {
45 throw new RangeError(`unrecognized minimum log level '${ignoreBelowLevel}'`);
46 }
47 const ignoreLevelIdx = logLevels.indexOf(ignoreBelowLevel);
48 logLevels.forEach((level) => {
49 const includeBackendLevel = (logLevels.indexOf(level) > ignoreLevelIdx) && this.backend[level]; // eslint-disable-line security/detect-object-injection
50 // eslint-disable-next-line security/detect-object-injection
51 this[level] = (includeBackendLevel) ?
52 nop :
53 (...args) => this.backend[level](this.payload(level, ...args)); // eslint-disable-line security/detect-object-injection
54 });
55 }
56
57
58 /**
59 * All the expected Console levels, but do nothing.
60 * Ordered from highest priority to lowest.
61 */
62 static get nullLogger() {
63 return {
64 error: nop,
65 warn: nop,
66 info: nop,
67 log: nop,
68 debug: nop,
69 };
70 }
71
72
73 /**
74 * Default of empty object when no asyncLocalStorage is defined.
75 * Overridden on instance when asyncLocalStorage is defined.
76 */
77 // eslint-disable-next-line class-methods-use-this
78 get asyncLogObject() {
79 return {};
80 }
81
82
83 /**
84 * Structure all expected log data into JSON string.
85 * @param {String} level
86 * @param {String} scope
87 * @param {String} message
88 * @param {Object} data
89 * @param {...any} other
90 * @returns {String} JSON string
91 */
92 payload(level, scope, message, data, ...other) {
93 if (this.sanitizationNeeded(data)) {
94 // Create copy of data so we are not changing anything important.
95 data = JSON.parse(JSON.stringify(data, this.jsonReplacer.bind(this)));
96 this.sanitize(data);
97 }
98
99 const now = new Date();
100 return JSON.stringify({
101 ...this.commonObject,
102 timestamp: now.toISOString(),
103 timestampMs: now.getTime(),
104 level: level,
105 scope: scope || '[unknown]',
106 message: message || '',
107 data: data || {},
108 ...(other.length && { other }),
109 ...this.asyncLogObject,
110 }, this.jsonReplacer.bind(this));
111 }
112
113
114 /**
115 * Determine if data needs sanitizing.
116 * @param {Object} data
117 * @returns {Boolean}
118 */
119 sanitizationNeeded(data) {
120 return this.dataSanitizers.some((sanitizer) => sanitizer(data, false));
121 }
122
123
124 /**
125 * Mogrify data.
126 * @param {Object} data
127 */
128 sanitize(data) {
129 this.dataSanitizers.forEach((sanitizer) => sanitizer(data));
130 }
131
132
133 /**
134 * Convert data into JSON.
135 * @param {String} _key
136 * @param {*} value
137 * @returns {String} serialized value
138 */
139 jsonReplacer(key, value) {
140 let replaced;
141
142 // Try applying all our replacers, until one does something.
143 this.jsonReplacers.every((replacer) => {
144 ({ replaced, value } = replacer(key, value));
145 return !replaced;
146 });
147 return value;
148 }
149
150 }
151
152 module.exports = Logger;