-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlog4js.ts
More file actions
116 lines (105 loc) · 2.99 KB
/
log4js.ts
File metadata and controls
116 lines (105 loc) · 2.99 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import * as fs from 'fs';
import * as log4js from 'log4js';
import * as path from 'path';
import * as util from 'util';
const isDev = process.env.NODE_ENV === 'development';
const logFile = process.env['LOGGER_PATH'];
const STACK_REGEX = /at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/;
function parseCallStack(error: Error, skipIdx = 4) {
const stackLines = error.stack!.split('\n').slice(skipIdx);
const lineMatch = STACK_REGEX.exec(stackLines[0]);
if (lineMatch && lineMatch.length === 6) {
return {
functionName: lineMatch[1],
fileName: lineMatch[2].replace(/^.*[\\/](src|dist|app)[\\/]/, ''), // we added replace to get rid of excessive path
lineNumber: parseInt(lineMatch[3], 10),
columnNumber: parseInt(lineMatch[4], 10),
callStack: stackLines.join('\n'),
};
}
return null;
}
function calculateCategory() {
const parsed = parseCallStack(new Error(), 3);
return parsed?.fileName.split('.')[0].split(path.sep).join('.');
}
export const ACCESS_LOG_CATEGORY = 'ACCESS-LOG';
const configuration: log4js.Configuration = {
appenders: {
console: {
type: 'console',
layout: {
type: 'pattern',
pattern: isDev
? '%[[%d] [%p] [%c] [%f:%l]%] %m%n' // Colored for development
: '[%d] [%p] [%c] %m%n',
},
},
},
categories: {
default: {
appenders: ['console'],
level: process.env['LOGGER_LEVEL'] || isDev ? 'trace' : 'info',
enableCallStack: isDev,
},
[ACCESS_LOG_CATEGORY]: {
appenders: ['console'],
level: 'info',
},
},
};
if (logFile) {
const logDir = path.dirname(logFile);
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
configuration.appenders.file = {
type: 'file',
filename: logFile,
maxLogSize: 5242880,
backups: 5,
};
configuration.categories.default.appenders = [
...configuration.categories.default.appenders,
'file',
];
}
log4js.configure(configuration);
export const shutdown = () => {
return new Promise<void>((resolve, reject) => {
log4js.shutdown(e => {
if (e) {
console.warn('Failed shutting down log4js', e);
}
resolve();
});
});
};
Object.defineProperty(Error.prototype, util.inspect.custom, {
value: function customErrorInspect(depth: any, options: any) {
return !isDev || this.isAxiosError === true ? this.toString() : this;
},
configurable: true,
writable: true,
});
declare global {
namespace NodeJS {
interface Global {
LOGGER: (suffix?: string | number, useAsIs?: boolean) => log4js.Logger;
}
}
}
global.LOGGER = (suffix?: string | number, useAsIs?: boolean) => {
let category: string | undefined;
if (useAsIs === true) {
category = suffix as string;
} else {
category = calculateCategory();
if (suffix) {
category = `${category}-${suffix}`;
}
}
const logger = log4js.getLogger(category);
logger.setParseCallStackFunction(parseCallStack); // override to get rid of filename excessive path
return logger;
};