-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.js
More file actions
183 lines (163 loc) · 5.67 KB
/
logger.js
File metadata and controls
183 lines (163 loc) · 5.67 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
/**
* guIDE — Centralized Logger
*
* Leveled logging (debug/info/warn/error) with persistent file output.
* All info+ entries written to rotating log file at:
* %APPDATA%/guide-ide/logs/guide-main.log (10MB max, 1 backup)
*
* Usage:
* const log = require('./main/logger');
* log.info('IDE', 'Service initialized');
* log.error('LLM', 'Failed to load', err.message);
*/
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
let level = LEVELS[process.env.LOG_LEVEL?.toLowerCase()] ?? LEVELS.debug;
// Log file path — derived from app name in package.json
const LOG_DIR = path.join(
process.env.APPDATA || path.join(os.homedir(), '.config'),
'guide-ide', 'logs'
);
const LOG_FILE = path.join(LOG_DIR, 'guide-main.log');
const MAX_SIZE = 10 * 1024 * 1024;
let stream = null;
let bytesWritten = 0;
let startupPathLogged = false;
function reportInternalLoggerError(context, err) {
try {
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`[Logger:${context}] ${msg}\n`);
} catch (_) {}
}
function ensureDir() {
try { if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true }); }
catch (err) { reportInternalLoggerError('ensureDir', err); }
}
function getStream() {
if (stream) return stream;
try {
ensureDir();
try { bytesWritten = fs.statSync(LOG_FILE).size; } catch (_) { bytesWritten = 0; }
stream = fs.createWriteStream(LOG_FILE, { flags: 'a' });
stream.on('error', (err) => {
reportInternalLoggerError('stream', err);
stream = null;
});
if (!startupPathLogged) {
startupPathLogged = true;
try {
stream.write(`${new Date().toISOString()} INFO [Logger] Log file path: ${LOG_FILE}\n`);
} catch (err) {
reportInternalLoggerError('startup-write', err);
}
}
return stream;
} catch (err) {
reportInternalLoggerError('getStream', err);
return null;
}
}
function rotate() {
if (bytesWritten < MAX_SIZE) return;
try {
if (stream) { stream.end(); stream = null; }
const backup = LOG_FILE + '.1';
try { fs.unlinkSync(backup); } catch (_) {}
fs.renameSync(LOG_FILE, backup);
bytesWritten = 0;
} catch (err) {
reportInternalLoggerError('rotate', err);
}
}
function writeLine(line) {
rotate();
const s = getStream();
if (s) {
try {
s.write(line + '\n');
bytesWritten += line.length + 1;
return;
} catch (err) {
reportInternalLoggerError('writeLine', err);
}
}
try { process.stderr.write(line + '\n'); } catch (_) {}
}
function fmtConsole(tag, args) {
const ts = new Date().toISOString().substring(11, 23);
return [`${ts} [${tag}]`, ...args];
}
function fmtFile(lvl, tag, args) {
const ts = new Date().toISOString();
const parts = args.map(a => {
if (a instanceof Error) return a.stack || a.message;
if (typeof a === 'object') { try { return JSON.stringify(a); } catch (_) { return String(a); } }
return String(a);
});
return `${ts} ${lvl.toUpperCase().padEnd(5)} [${tag}] ${parts.join(' ')}`;
}
const logger = {
setLevel(l) { level = LEVELS[l] ?? LEVELS.info; },
getLevel() { return Object.keys(LEVELS).find(k => LEVELS[k] === level) || 'info'; },
getLogPath() { return LOG_FILE; },
debug(tag, ...args) {
if (level <= LEVELS.debug) {
console.log(...fmtConsole(tag, args));
writeLine(fmtFile('debug', tag, args));
}
},
info(tag, ...args) {
if (level <= LEVELS.info) console.log(...fmtConsole(tag, args));
writeLine(fmtFile('info', tag, args));
},
warn(tag, ...args) {
if (level <= LEVELS.warn) console.warn(...fmtConsole(tag, args));
writeLine(fmtFile('warn', tag, args));
},
error(tag, ...args) {
if (level <= LEVELS.error) console.error(...fmtConsole(tag, args));
writeLine(fmtFile('error', tag, args));
},
close() { if (stream) { stream.end(); stream = null; } },
/**
* Intercept all console.log/warn/error so every module's output goes to
* the persistent log file. Call once at startup from electron-main.js.
*/
installConsoleIntercepts() {
const origLog = console.log.bind(console);
const origWarn = console.warn.bind(console);
const origError = console.error.bind(console);
const stringify = (a) => {
if (a instanceof Error) return a.stack || a.message;
if (typeof a === 'object') { try { return JSON.stringify(a); } catch (_) { return String(a); } }
return String(a);
};
console.log = (...args) => {
origLog(...args);
writeLine(`${new Date().toISOString()} LOG ${args.map(stringify).join(' ')}`);
};
console.warn = (...args) => {
origWarn(...args);
writeLine(`${new Date().toISOString()} WARN ${args.map(stringify).join(' ')}`);
};
console.error = (...args) => {
origError(...args);
writeLine(`${new Date().toISOString()} ERROR ${args.map(stringify).join(' ')}`);
};
process.on('uncaughtException', (err) => {
writeLine(`${new Date().toISOString()} FATAL [UncaughtException] ${err.stack || err.message || err}`);
});
process.on('unhandledRejection', (reason) => {
const msg = reason instanceof Error ? (reason.stack || reason.message) : String(reason);
writeLine(`${new Date().toISOString()} ERROR [UnhandledRejection] ${msg}`);
});
},
};
// Session start marker — load version from package.json with safe fallback
let _guideVersion = '2.0.0';
try { _guideVersion = require('./package.json').version || _guideVersion; } catch (_) {}
writeLine(`\n${'='.repeat(80)}\n${new Date().toISOString()} SESSION START — guIDE v${_guideVersion}\n${'='.repeat(80)}`);
module.exports = logger;