Skip to content

Commit

Permalink
fix(logger): Do not log twice if logfile is the same as stdout redire…
Browse files Browse the repository at this point in the history
…ction (#691)
  • Loading branch information
ccoors committed Feb 16, 2021
1 parent 4bd09c8 commit 2bd4c82
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
21 changes: 17 additions & 4 deletions lib/Logger.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const {EventEmitter} = require("events");
const fs = require("fs");
const util = require("util");
const Tools = require("./Tools");

const LogFileOptions = Object.freeze({
flags: "as"
Expand Down Expand Up @@ -46,14 +47,24 @@ class Logger {
LogLevel = LogLevels[value];
}
static set LogFile(filename) {
if (LogFilename === filename) {
if (Tools.ARE_SAME_FILES(LogFilename, filename)) {
// We are already writing to that file
return;
}

if (LogFile) {
LogFile.close();
LogFile = null;
}
LogFilename = filename;
LogFile = fs.createWriteStream(LogFilename, LogFileOptions);
// Check if output is already redirected to that same file. If
// it is, we do not need to write to that same file, because that
// would lead to duplicate log entries.
// Setting the LogFilename anyway ensures that the UI Log still works.
if (!Tools.ARE_SAME_FILES(filename, "/proc/self/fd/1")) {
LogFilename = filename;
LogFile = fs.createWriteStream(LogFilename, LogFileOptions);
}

Logger.log("info", "Set Logfile to " + filename);
}
Expand All @@ -75,8 +86,10 @@ class Logger {
}
return util.inspect(arg);
}).join(" ");
LogFile.write(logLine);
LogFile.write("\n");
if (LogFile) {
LogFile.write(logLine);
LogFile.write("\n");
}
LogEventEmitter.emit("LogMessage", logLine);
}
}
Expand Down
14 changes: 14 additions & 0 deletions lib/Tools.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,20 @@ class Tools {
}
}

static ARE_SAME_FILES(filepath1, filepath2) {
if (filepath1 === filepath2) {
return true;
}

try {
const stat1 = fs.statSync(filepath1, {bigint: true});
const stat2 = fs.statSync(filepath2, {bigint: true});
return (stat1.dev === stat2.dev && stat1.ino === stat2.ino);
} catch (e) {
return false;
}
}

static BUFFER_IS_GZIP(buf) {
return Buffer.isBuffer(buf) && buf[0] === 0x1f && buf[1] === 0x8b;
}
Expand Down

0 comments on commit 2bd4c82

Please sign in to comment.