Skip to content

Commit d85c1f2

Browse files
committed
Improve error handling
1 parent 0f25454 commit d85c1f2

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

lib/src/logger.ts

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ export const createLogger = (config: LoggerConfig = {}) => {
1717
file: config.levels?.file ?? ["info", "warn", "error"],
1818
};
1919

20-
if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
20+
try {
21+
if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
22+
} catch (error) {
23+
console.warn(`Failed to create log directory: ${error}`);
24+
}
2125

2226
const buffers = new Map<string, LogEntry[]>();
2327
const streams = new Map<string, fs.WriteStream>();
@@ -55,15 +59,25 @@ export const createLogger = (config: LoggerConfig = {}) => {
5559
if (mode === "memory") {
5660
const timestamp = new Date().toISOString().replace(/:/g, "-");
5761
for (const [fileId, entries] of buffers.entries()) {
58-
const filePath = path.join(
59-
logDir,
60-
singleFile ? `combined-${timestamp}.log` : `${fileId}-${timestamp}.log`,
61-
);
62-
const lines = entries.map(e => `[${e.timestamp}] [${e.level.toUpperCase()}] ${e.message}`);
63-
fs.writeFileSync(filePath, lines.join("\n") + "\n", { flag: "a" });
62+
try {
63+
const filePath = path.join(
64+
logDir,
65+
singleFile ? `combined-${timestamp}.log` : `${fileId}-${timestamp}.log`,
66+
);
67+
const lines = entries.map(e => `[${e.timestamp}] [${e.level.toUpperCase()}] ${e.message}`);
68+
fs.writeFileSync(filePath, lines.join("\n") + "\n", { flag: "a" });
69+
} catch (error) {
70+
console.warn(`Failed to write log file for ${fileId}: ${error}`);
71+
}
72+
}
73+
}
74+
for (const s of streams.values()) {
75+
try {
76+
s.end();
77+
} catch (error) {
78+
console.warn(`Failed to close log stream: ${error}`);
6479
}
6580
}
66-
for (const s of streams.values()) s.end();
6781
};
6882

6983
return {

0 commit comments

Comments
 (0)