-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (71 loc) · 1.93 KB
/
index.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
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const LEVELS = {
info: "INFO",
debug: "DEBUG",
warn: "WARN",
error: "ERROR"
}
class FileLogger {
constructor(prefix, logPath) {
this.prefix = prefix;
this.logFilePath = logPath || path.join(__dirname, 'log');
}
child(prefix) {
return new FileLogger(`${this.prefix} ${prefix}`, this.logFilePath)
}
logInfo(message) {
this._log(message, 'info');
}
logDebug(message) {
this._log(message, 'debug');
}
logWarn(message) {
this._log(message, 'warn');
}
logError(message) {
this._log(message, 'error');
}
_log(message, level = 'info') {
let logText;
// Check the type of the input and handle accordingly
if (typeof message === 'string') {
logText = message;
} else if (typeof message === 'object') {
// Stringify the object to make it human-readable
logText = JSON.stringify(message, null, 2);
} else {
// If the input is not a string or an object, convert it to a string
logText = String(message);
}
const finalText = `${this.prefix} [${LEVELS[level]}] ${logText}`;
this._appendToFile(finalText);
this._logStdOut(logText, level);
}
_appendToFile(text) {
try {
fs.appendFileSync(this.logFilePath, text + '\n');
} catch (err) {
if (err.code === 'ENOENT') {
// If the file doesn't exist, create it and try again
fs.writeFileSync(this.logFilePath, '');
fs.appendFileSync(this.logFilePath, text + '\n');
} else {
console.error('Error appending text to the log file:', err);
}
}
}
_logStdOut(message, level = 'info') {
const request = {
jsonrpc: '2.0',
method: 'log',
params: {level: level, message: message},
};
process.stdout.write(JSON.stringify(request));
}
}
export default FileLogger;