Skip to content
This repository has been archived by the owner on Jan 14, 2022. It is now read-only.

Commit

Permalink
Merge pull request #831 from LiskHQ/830-improved-logger
Browse files Browse the repository at this point in the history
Improved logger - Closes #830
  • Loading branch information
MichalTuleja authored Nov 27, 2018
2 parents f610989 + 1dc4ecb commit 64a452c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 14 deletions.
2 changes: 1 addition & 1 deletion config.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ config.cacheTTL = 20;
// Collect logs (true - enabled, false - disabled)
config.log.enabled = true;
// Output for logs - can be device file or ordinary path
config.log.file = './logs/explorer.log';
config.log.output = ['/dev/stdout', './logs/explorer.log'];
// Log level - (trace, debug, info, warn, error)
config.log.level = 'info';

Expand Down
39 changes: 26 additions & 13 deletions utils/logger.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,22 @@ const flatstr = require('flatstr');
const newConsole = require('console').Console;
const config = require('../config');

const output = fs.createWriteStream(config.log.file, { flags: 'a' });
const myConsole = new newConsole(output, output);
const defaultOutput = '/dev/stdout';

if (!Array.isArray(config.log.output)) {
if (typeof config.log.output === 'string') {
config.log.output = [config.log.output];
} else if (typeof config.log.file === 'string') {
config.log.output = [config.log.file];
} else {
config.log.output = [defaultOutput];
}
}

const logOutputs = config.log.output.map((outputPath) => {
const fileOutput = fs.createWriteStream(outputPath, { flags: 'a' });
return new newConsole(fileOutput, fileOutput);
});

const levels = {
trace: 0,
Expand All @@ -35,25 +49,24 @@ const logger = {};
logger.doLog = function doLog(level, msg, extra) {
if (config.log.enabled) {
const timestamp = Date.now();

// const stringMsg = typeof msg === 'string' ? msg : JSON.stringify(msg);
// const parsedMsg = stringMsg.replace(/(\r\n|\n|\r)/gm, ' ');
let outputString;

if (extra) {
const stringExtra = typeof extra === 'string' ? extra : JSON.stringify(extra);
const parsedExtra = stringExtra.replace(/(\r\n|\n|\r)/gm, ' ');
myConsole.log(flatstr(safeStringify({
level,
timestamp,
message: `${msg} ${parsedExtra}`,
})));
outputString = `${msg} ${parsedExtra}`;
} else {
myConsole.log(flatstr(safeStringify({
outputString = msg;
}

logOutputs.map((logOutput) => {
logOutput.log(flatstr(safeStringify({
level,
timestamp,
message: msg,
message: outputString,
})));
}
return logOutput;
});
}
};

Expand Down

0 comments on commit 64a452c

Please sign in to comment.