-'use strict';
-
-/**
- * Log as JSON to stdout/stderr.
- */
-
-const common = require('./common');
-
-// This is uncomfortable, but is the simplest way to let logging work for BigInts.
-// TODO: revisit with better solution
-BigInt.prototype.toJSON = function() {
- return this.toString();
-}
-
-// Also uncomfortable
-Object.defineProperty(Error.prototype, 'toJSON', {
- configurable: true,
- value: function () {
- const result = {};
- const dupKey = function (key) {
- // eslint-disable-next-line security/detect-object-injection
- result[key] = this[key];
- };
- Object.getOwnPropertyNames(this).forEach(dupKey, this);
- return result;
- },
-});
-
-const defaultOptions = {
- ignoreBelowLevel: 'debug',
- backend: console,
-};
-
-class Logger {
- constructor(options = {}) {
- common.setOptions(this, defaultOptions, options);
-
- this.logLevels = [
- 'error',
- 'warn',
- 'info',
- 'log',
- 'debug',
- ];
-
- const ignoreLevelIdx = this.logLevels.indexOf(this.ignoreBelowLevel);
- this.logLevels.forEach((level) => {
- // eslint-disable-next-line security/detect-object-injection
- this[level] = (this.logLevels.indexOf(level) > ignoreLevelIdx) ?
- () => {} :
- Logger.levelTemplateFn(this.backend, level);
- });
- }
-
- static levelTemplateFn(backend, level) {
- return function (...args) {
- // eslint-disable-next-line security/detect-object-injection
- backend[level](Logger.payload(level, ...args));
- };
- }
-
- static payload(level, scope, message, data, ...other) {
- return JSON.stringify({
- timestamp: Date.now(),
- level: level,
- scope: scope || '[unknown]',
- message: message || '',
- data: data || {},
- ...(other.length && { other }),
- });
- }
-}
-
-module.exports = Logger;