-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.js
More file actions
74 lines (64 loc) · 2.05 KB
/
logger.js
File metadata and controls
74 lines (64 loc) · 2.05 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
/**
* Простой логгер для mpt-replacement-service.
* Уровни: debug, info, warn, error.
* Пишет в stdout и опционально в файл (в папке сервиса или DATA_DIR/logs).
*/
const fs = require("fs");
const path = require("path");
const LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
const LOG_LEVEL = (process.env.LOG_LEVEL || "info").toLowerCase();
const MIN_LEVEL = LEVELS[LOG_LEVEL] ?? LEVELS.info;
const LOG_DIR =
process.env.LOG_DIR ||
path.join(process.env.DATA_DIR || path.join(__dirname, "data"), "logs");
const LOG_FILE = process.env.LOG_FILE || path.join(LOG_DIR, "service.log");
let stream = null;
function ensureLogDir() {
const dir = path.dirname(LOG_FILE);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function getStream() {
if (stream) return stream;
ensureLogDir();
stream = fs.createWriteStream(LOG_FILE, { flags: "a" });
return stream;
}
function format(level, ...args) {
const ts = new Date().toLocaleString("sv-SE", { timeZone: "Europe/Moscow" });
const msg = args
.map((a) => (typeof a === "object" ? JSON.stringify(a) : String(a)))
.join(" ");
return `[${ts}] [${level.toUpperCase()}] ${msg}\n`;
}
function write(level, ...args) {
const line = format(level, ...args);
process.stdout.write(line);
try {
getStream().write(line);
} catch (e) {
process.stderr.write(`[логгер] ошибка записи: ${e.message}\n`);
}
}
function log(level, ...args) {
if (LEVELS[level] >= MIN_LEVEL) {
write(level, ...args);
}
}
module.exports = {
debug: (...args) => log("debug", ...args),
info: (...args) => log("info", ...args),
warn: (...args) => log("warn", ...args),
error: (...args) => log("error", ...args),
child(prefix) {
return {
debug: (...a) => log("debug", prefix, ...a),
info: (...a) => log("info", prefix, ...a),
warn: (...a) => log("warn", prefix, ...a),
error: (...a) => log("error", prefix, ...a),
};
},
getLogPath: () => LOG_FILE,
getLogDir: () => LOG_DIR,
};