-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.js
94 lines (85 loc) · 2.58 KB
/
logger.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
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
const { createLogger, format, transports } = require('winston');
const LokiTransport = require('winston-loki');
const ENABLE_LOKI = process.env.ENABLE_LOKI === 'true';
const LOGLEVEL = [
'silly',
'debug',
'verbose',
'http',
'info',
'warn',
'error',
].includes(process.env.DEFAULT_LOGLEVEL) ? process.env.DEFAULT_LOGLEVEL : 'info';
const token_values = Object.entries(process.env).reduce((acc, [name, value]) => {
if (name.endsWith('_TOKEN') && value.length) {
acc.push(value)
}
return acc;
}, []);
const replaceToken = format((options) => {
for (let key of Object.keys(options)) {
if (typeof options[key] !== 'string') continue;
token_values.forEach(token => {
options[key] = options[key].replaceAll(token, '***')
});
}
return options;
});
const logger_options = {
transports: [
new transports.Console({
format: format.combine(
replaceToken(),
format.timestamp(),
format.colorize(),
format.printf(options => {
return `${options.timestamp} - ${options.module} - ${options.level} - ${options.level === 'error' ? options.message : options.message.replace(/\n/gm, '\\n')}\
${options.error ? ` : ${typeof options.error === 'object' ? JSON.stringify(options.error) : options.error}` : ''}`;
})
),
level: LOGLEVEL,
}),
]
};
if (process.env?.ENV === 'dev') {
logger_options.transports.push(
new transports.File({
format: format.combine(
replaceToken(),
format.timestamp(),
format.json()
),
level: 'silly',
filename: `combined.log`
})
)
}
if (ENABLE_LOKI) {
const {
LOKI_HOST = '',
LOKI_LABELS = '',
LOKI_USER = '',
LOKI_PASS = '',
RAILWAY_GIT_COMMIT_MESSAGE: LAST_COMMIT,
LOKI_LOGLEVEL = LOGLEVEL
} = process.env;
const VERSION = require('./package.json').version;
logger_options.transports.push(
new LokiTransport({
host: LOKI_HOST,
json: true,
labels: {
...JSON.parse(LOKI_LABELS),
version: VERSION,
last_commit: LAST_COMMIT,
},
basicAuth: `${LOKI_USER}:${LOKI_PASS}`,
format: format.combine(
replaceToken(),
format.json()
),
level: LOKI_LOGLEVEL,
})
)
}
module.exports = createLogger(logger_options);