fix ordering of replacing and de-cycling to work correctly in some situations
[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 const replacer = this.getReplacer();
94
95 if (this.sanitizationNeeded(data)) {
96 // Create copy of data so we are not changing anything important.
97 data = structuredClone(data);
98 this.sanitize(data);
99 }
100
101 const now = new Date();
102 const logPayload = {
103 ...this.commonObject,
104 timestamp: now.toISOString(),
105 timestampMs: now.getTime(),
106 level: level,
107 scope: scope || '[unknown]',
108 message: message || '',
109 data: data || {},
110 ...(other.length && { other }),
111 ...this.asyncLogObject,
112 };
113 return JSON.stringify(logPayload, replacer);
114 }
115
116
117 /**
118 * Determine if data needs sanitizing.
119 * @param {Object} data
120 * @returns {Boolean}
121 */
122 sanitizationNeeded(data) {
123 return this.dataSanitizers.some((sanitizer) => sanitizer(data, false));
124 }
125
126
127 /**
128 * Mogrify data.
129 * @param {Object} data
130 */
131 sanitize(data) {
132 this.dataSanitizers.forEach((sanitizer) => sanitizer(data));
133 }
134
135
136 /**
137 * Return a replacer function which does de-cycling, as well as the rest of our replacers.
138 */
139 getReplacer() {
140 const ancestors = [];
141 const loggerReplacers = this.jsonReplacers;
142 return function cycleReplacer(key, value) {
143 loggerReplacers.every((replacer) => {
144 const oldValue = value;
145 value = replacer(key, value);
146 return oldValue === value;
147 });
148 if (typeof value === 'object' && value !== null) {
149 // 'this' is object where key/value came from
150 while (ancestors.length > 0 && ancestors.at(-1) !== this) {
151 ancestors.pop();
152 }
153 if (ancestors.includes(value)) { // eslint-disable-line security/detect-object-injection
154 return '[Circular]';
155 } else {
156 ancestors.push(value);
157 }
158 }
159
160 return value;
161 }
162 }
163
164 }
165
166 module.exports = Logger;