Skip to content

Commit d59993a

Browse files
committed
fix(server): potential race condition when rotating logs
1 parent 91f3bc4 commit d59993a

File tree

1 file changed

+10
-7
lines changed
  • apps/server/src/services

1 file changed

+10
-7
lines changed

apps/server/src/services/log.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ if (!fs.existsSync(dataDir.LOG_DIR)) {
1212
fs.mkdirSync(dataDir.LOG_DIR, 0o700);
1313
}
1414

15-
let logFile!: fs.WriteStream;
15+
let logFile: fs.WriteStream | undefined;
1616

1717
const SECOND = 1000;
1818
const MINUTE = 60 * SECOND;
@@ -107,17 +107,20 @@ function initLogFile() {
107107
todaysMidnight = getTodaysMidnight();
108108

109109
const logPath = `${dataDir.LOG_DIR}/trilium-${formatDate()}.log`;
110+
const isRotating = !!logFile;
110111

111-
if (logFile) {
112-
logFile.end();
112+
if (isRotating) {
113+
logFile!.end();
114+
}
115+
116+
logFile = fs.createWriteStream(logPath, { flags: "a" });
113117

114-
// Clean up old log files when rotating to a new file
118+
// Clean up old log files when rotating to a new file
119+
if (isRotating) {
115120
cleanupOldLogFiles().catch(() => {
116121
// Ignore cleanup errors
117122
});
118123
}
119-
120-
logFile = fs.createWriteStream(logPath, { flags: "a" });
121124
}
122125

123126
function checkDate(millisSinceMidnight: number) {
@@ -141,7 +144,7 @@ function log(str: string | Error) {
141144

142145
millisSinceMidnight = checkDate(millisSinceMidnight);
143146

144-
logFile.write(`${formatTime(millisSinceMidnight)} ${str}${EOL}`);
147+
logFile!.write(`${formatTime(millisSinceMidnight)} ${str}${EOL}`);
145148

146149
console.log(str);
147150
}

0 commit comments

Comments
 (0)