4 * Log as JSON to stdout/stderr.
7 const common
= require('./common');
9 // This is uncomfortable, but is the simplest way to let logging work for BigInts.
10 // TODO: revisit with better solution
11 BigInt
.prototype.toJSON = function() {
12 return this.toString();
15 // Also uncomfortable, but let us log Errors reasonably.
16 Object
.defineProperty(Error
.prototype, 'toJSON', {
18 writable: true, // Required to let Axios override on its own Errors
21 const dupKey = function (key
) {
22 // eslint-disable-next-line security/detect-object-injection
23 result
[key
] = this[key
];
25 Object
.getOwnPropertyNames(this)
26 // .filter((prop) => !(prop in []))
27 .forEach(dupKey
, this);
34 * Wrap backend calls with payload normalization.
35 * @param {Object} options
36 * @param {*} backend Console style interface
37 * @param {Object} options.logger
38 * @param {String} options.logger.ignoreBelowLevel minimum level to log
39 * @param {String} options.nodeId
41 constructor(options
, backend
= console
) {
42 const logLevels
= Object
.keys(common
.nullLogger
);
43 const ignoreBelowLevel
= options
&& options
.logger
&& options
.logger
.ignoreBelowLevel
|| 'debug';
44 this.nodeId
= options
.nodeId
;
46 if (!logLevels
.includes(ignoreBelowLevel
)) {
47 throw new RangeError(`unrecognized minimum log level '${ignoreBelowLevel}'`);
49 const ignoreLevelIdx
= logLevels
.indexOf(ignoreBelowLevel
);
50 logLevels
.forEach((level
) => {
51 // eslint-disable-next-line security/detect-object-injection
52 this[level
] = (logLevels
.indexOf(level
) > ignoreLevelIdx
) ?
54 this.levelTemplateFn(backend
, level
);
58 levelTemplateFn(backend
, level
) {
59 // eslint-disable-next-line security/detect-object-injection
60 if (!(level
in backend
) || typeof backend
[level
] !== 'function') {
64 // eslint-disable-next-line security/detect-object-injection
65 return (...args
) => backend
[level
](this.payload(level
, ...args
));
68 payload(level
, scope
, message
, data
, ...other
) {
69 const now
= new Date();
70 return JSON
.stringify({
72 timestamp: now
.toISOString(),
73 timestampMs: now
.getTime(),
75 scope: scope
|| '[unknown]',
76 message: message
|| '',
78 ...(other
.length
&& { other
}),
83 module
.exports
= Logger
;