-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
51 lines (44 loc) · 1.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
const fs = require("fs");
const path = require("path");
/**
* Logs a message to a specified directory and log file.
* @param {string} logDir - The directory to save the log file.
* @param {string} logType - The type of log (e.g., 'error', 'info', 'console').
* @param {string} message - The log message.
*/
const logMessage = (logDir, logType, message) => {
const logDirPath = path.resolve(__dirname, logDir);
if (!fs.existsSync(logDirPath)) {
fs.mkdirSync(logDirPath, { recursive: true });
}
const logFilePath = path.join(logDirPath, `${logType}.log`);
const timestamp = new Date().toISOString();
const sanitizedMessage = message.replace(/[<>:"/\\|?*\x00-\x1F]/g, ""); // Remove invalid characters
const logEntry = `${timestamp} - ${logType.toUpperCase()}: ${sanitizedMessage}\n`;
fs.appendFile(logFilePath, logEntry, (err) => {
if (err) throw err;
});
};
/**
* Logs an error message.
* @param {string} logDir - The directory to save the log file.
* @param {string} message - The log message.
*/
const logError = (logDir, message) => logMessage(logDir, "error", message);
/**
* Logs an info message.
* @param {string} logDir - The directory to save the log file.
* @param {string} message - The log message.
*/
const logInfo = (logDir, message) => logMessage(logDir, "info", message);
/**
* Logs a console message.
* @param {string} logDir - The directory to save the log file.
* @param {string} message - The log message.
*/
const logConsole = (logDir, message) => logMessage(logDir, "console", message);
module.exports = {
logError,
logInfo,
logConsole,
};