-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredirect-output.js
43 lines (38 loc) · 1.41 KB
/
redirect-output.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const fs = require('fs');
const fecha = require('fecha');
const { PATHS } = require('./consts.js');
/**
* Redirects stdout and stderr to provided log paths.
* stdout only if process is run with --debug, otherwise its output is lost.
*/
function setup() {
// Redirect uncaught/unhandled things to console.error (makes logging them to file possible)
// ------------------------------------------------------------------------------
process.on('uncaughtException', (err) => {
console.error(err);
process.exit(1);
});
process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at:', p, 'reason:', reason);
process.exit(1);
});
// Redirect stdout/stderr to log files if app is run as packaged .exe
// --------------------------------------------------------------------
const stdoutFile = fs.createWriteStream(PATHS.DEBUG_LOG, { flags: 'a' });
// ignore stdout if not run with --debug
const isDebug = process.argv.includes('--debug');
process.stdout.write = function (string, encoding) {
if (isDebug) {
string = `${fecha.format(new Date(), 'HH:mm:ss.SSS')}: ${string}`;
stdoutFile.write(string, encoding);
}
};
const stderrFile = fs.createWriteStream(PATHS.ERROR_LOG, { flags: 'a' });
process.stderr.write = function (string, encoding) {
string = `${fecha.format(new Date(), 'HH:mm:ss.SSS')}: ${string}`;
stderrFile.write(string, encoding);
};
}
module.exports = {
setup,
};