-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathcommon.js
More file actions
75 lines (67 loc) · 2.35 KB
/
common.js
File metadata and controls
75 lines (67 loc) · 2.35 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const { join } = require('path');
// eslint-disable-next-line import/no-dynamic-require
const common = require(join(__dirname, '..', 'common'));
const { program } = common;
const { paths } = common.system;
const osName = process.platform.replace('win32', 'windows').replace('darwin', 'mac');
const fs = require('fs');
const fetchEnvVar = require('../utils/fetch-env-var');
common.helpers = require('./helpers');
// TODO: fix the two commons imports
const logFile = program.logfile || common.helpers.running_on_background()
? program.logfile || paths.log_file
: null;
const logLevel = fetchEnvVar('DEBUG') && fetchEnvVar('DEBUG').localeCompare('true') === 0 ? 'debug' : 'info';
common.logger = require('petit').new({
level: logLevel,
file: logFile,
rotate: true,
size: 2000000,
limit: 9,
compress: true,
dest: paths.config,
});
// Suppress EACCES errors from logger (permission denied to write log file)
if (common.logger && common.logger.stream) {
const originalEmit = common.logger.stream.emit;
common.logger.stream.emit = function (event, err) {
// Silently ignore EACCES errors from log file writes
if (event === 'error' && err && err.code === 'EACCES') {
return false;
}
return originalEmit.apply(this, arguments);
};
}
common.logger_restarts = osName === 'windows' ? require('petit').new({
level: logLevel,
file: paths.log_restarts,
rotate: false,
size: 200,
limit: 0,
compress: false,
dest: paths.config,
}) : () => {};
common.writeFileLoggerRestart = (textToWrite) => {
if (!common.helpers.running_on_background() || osName !== 'windows') return;
fs.appendFile(paths.log_restarts, `${textToWrite}\n`, () => {});
};
common.countLinesLoggerRestarts = () => {
if (!common.helpers.running_on_background() || osName !== 'windows') return;
const fileBuffer = fs.readFileSync(paths.log_restarts);
const toString = fileBuffer.toString();
const splitLines = toString.split('\n');
if (splitLines.length > 5) {
try {
const fd = fs.openSync(paths.log_restarts, 'w');
if (fd !== -1) {
fs.writeSync(fd, splitLines.slice(1, 6).join('\n'));
fs.closeSync(fd);
} else {
throw new Error('There was an error when trying to open the file');
}
} catch (err) {
common.logger.info(`Error writing file ${paths.log_restarts}: ${err.message}`);
}
}
};
module.exports = common;