-
Notifications
You must be signed in to change notification settings - Fork 269
Expand file tree
/
Copy pathlogger.js
More file actions
283 lines (243 loc) · 7.08 KB
/
logger.js
File metadata and controls
283 lines (243 loc) · 7.08 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*******************************************************************************
Highcharts Export Server
Copyright (c) 2016-2024, Highsoft
Licenced under the MIT licence.
Additionally a valid Highcharts license is required for use.
See LICENSE file in root for details.
*******************************************************************************/
import { appendFile, existsSync, mkdirSync } from 'fs';
// Map of styles (colors, thickness) and their ANSI escape codes
// used instead of the 'colors' package;
export const style = {
red: '\x1b[31m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
green: '\x1b[32m',
white: '\x1b[37m',
gray: '\x1b[90m',
reset: '\x1b[0m',
bold: '\x1b[1m',
underline: '\x1b[4m'
};
// The available colors
const colors = ['red', 'yellow', 'blue', 'gray', 'green'];
// The default logging config
let logging = {
// Flags for logging status
toConsole: true,
toFile: false,
pathCreated: false,
// Log levels
levelsDesc: [
{
title: 'error',
color: colors[0]
},
{
title: 'warning',
color: colors[1]
},
{
title: 'notice',
color: colors[2]
},
{
title: 'verbose',
color: colors[3]
},
{
title: 'benchmark',
color: colors[4]
}
],
// Log listeners
listeners: []
};
/**
* Logs the provided texts to a file, if file logging is enabled. It creates
* the necessary directory structure if not already created and appends the
* content, including an optional prefix, to the specified log file.
*
* @param {string[]} texts - An array of texts to be logged.
* @param {string} prefix - An optional prefix to be added to each log entry.
*/
const logToFile = (texts, prefix) => {
if (!logging.pathCreated) {
// Create if does not exist
!existsSync(logging.dest) && mkdirSync(logging.dest);
// We now assume the path is available, e.g. it's the responsibility
// of the user to create the path with the correct access rights.
logging.pathCreated = true;
}
// Add the content to a file
appendFile(
`${logging.dest}${logging.file}`,
[prefix].concat(texts).join(' ') + '\n',
(error) => {
if (error) {
console.log(`[logger] Unable to write to log file: ${error}`);
logging.toFile = false;
}
}
);
};
/**
* Logs a message. Accepts a variable amount of arguments. Arguments after
* `level` will be passed directly to console.log, and/or will be joined
* and appended to the log file.
*
* @param {any} args - An array of arguments where the first is the log level
* and the rest are strings to build a message with.
*/
export const log = (...args) => {
const [newLevel, ...texts] = args;
// Current logging options
const { levelsDesc, level } = logging;
// Check if log level is within a correct range or is a benchmark log
if (
newLevel !== 5 &&
(newLevel === 0 || newLevel > level || level > levelsDesc.length)
) {
return;
}
// Get rid of the GMT text information
const newDate = new Date().toString().split('(')[0].trim();
// Create a message's prefix
const prefix = `${newDate} [${levelsDesc[newLevel - 1].title}] -`;
// Call available log listeners
logging.listeners.forEach((fn) => {
fn(prefix, texts.join(' '));
});
// Log to console
if (logging.toConsole) {
console.log.apply(
undefined,
[
`${style[logging.levelsDesc[newLevel - 1].color]}`,
prefix.toString(),
`${style.reset}`
].concat(texts)
);
}
// Log to file
if (logging.toFile) {
logToFile(texts, prefix);
}
};
/**
* Logs an error message with its stack trace. Optionally, a custom message
* can be provided.
*
* @param {number} level - The log level.
* @param {Error} error - The error object.
* @param {string} customMessage - An optional custom message to be logged along
* with the error.
*/
export const logWithStack = (newLevel, error, customMessage) => {
// Get the main message
const mainMessage = customMessage || error.message;
// Current logging options
const { level, levelsDesc } = logging;
// Check if log level is within a correct range
if (newLevel === 0 || newLevel > level || level > levelsDesc.length) {
return;
}
// Get rid of the GMT text information
const newDate = new Date().toString().split('(')[0].trim();
// Create a message's prefix
const prefix = `${newDate} [${levelsDesc[newLevel - 1].title}] -`;
// If the customMessage exists, we want to display the whole stack message
const stackMessage =
error.message !== error.stackMessage || error.stackMessage === undefined
? error.stack
: error.stack.split('\n').slice(1).join('\n');
// Combine custom message or error message with error stack message
const texts = [mainMessage, '\n', stackMessage];
// Log to console
if (logging.toConsole) {
console.log.apply(
undefined,
[
`${style[logging.levelsDesc[newLevel - 1].color]}`,
prefix.toString(),
`${style.reset}`
].concat([mainMessage[colors[newLevel - 1]], '\n', stackMessage])
);
}
// Call available log listeners
logging.listeners.forEach((fn) => {
fn(prefix, texts.join(' '));
});
// Log to file
if (logging.toFile) {
logToFile(texts, prefix);
}
};
/**
* Sets the log level to the specified value. Log levels are (0 = no logging,
* 1 = error, 2 = warning, 3 = notice, 4 = verbose or 5 = benchmark)
*
* @param {number} newLevel - The new log level to be set.
*/
export const setLogLevel = (newLevel) => {
if (newLevel >= 0 && newLevel <= logging.levelsDesc.length) {
logging.level = newLevel;
}
};
/**
* Enables file logging with the specified destination and log file.
*
* @param {string} logDest - The destination path for log files.
* @param {string} logFile - The log file name.
*/
export const enableFileLogging = (logDest, logFile) => {
// Update logging options
logging = {
...logging,
dest: logDest || logging.dest,
file: logFile || logging.file,
toFile: true
};
if (logging.dest.length === 0) {
return log(1, '[logger] File logging initialization: no path supplied.');
}
if (!logging.dest.endsWith('/')) {
logging.dest += '/';
}
};
/**
* Initializes logging with the specified logging configuration.
*
* @param {Object} loggingOptions - The logging configuration object.
*/
export const initLogging = (loggingOptions) => {
// Set all the logging options on our logging module object
for (const [key, value] of Object.entries(loggingOptions)) {
logging[key] = value;
}
// Set the log level
setLogLevel(loggingOptions && parseInt(loggingOptions.level));
// Set the log file path and name
if (loggingOptions && loggingOptions.dest && loggingOptions.toFile) {
enableFileLogging(
loggingOptions.dest,
loggingOptions.file || 'highcharts-export-server.log'
);
}
};
/**
* Adds a listener function to the logging system.
*
* @param {function} fn - The listener function to be added.
*/
export const listen = (fn) => {
logging.listeners.push(fn);
};
export default {
log,
logWithStack,
setLogLevel,
enableFileLogging,
initLogging,
listen
};