Skip to content

Build your personal knowledge base with Trilium Notes

fix(server): reintegrate backend log mechanism

Elian Doran73743b62364f
diff --git a/apps/server/src/log_provider.ts b/apps/server/src/log_provider.ts
new file mode 100644
index 0000000000..38161f0a4b
--- /dev/null
+++ b/apps/server/src/log_provider.ts
@@ -0,0 +1,195 @@
+import { LogService } from "@triliumnext/core";
+import type { Request, Response } from "express";
+import fs from "fs";
+import { EOL } from "os";
+import path from "path";
+
+import cls from "./services/cls.js";
+import config, { LOGGING_DEFAULT_RETENTION_DAYS } from "./services/config.js";
+import dataDir from "./services/data_dir.js";
+
+const SECOND = 1000;
+const MINUTE = 60 * SECOND;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+
+const MINIMUM_FILES_TO_KEEP = 7;
+
+const requestBlacklist = ["/app", "/images", "/stylesheets", "/api/recent-notes"];
+
+export default class ServerLogService extends LogService {
+ private logFile: fs.WriteStream | undefined;
+ private todaysMidnight!: Date;
+
+ constructor() {
+ super();
+ fs.mkdirSync(dataDir.LOG_DIR, { recursive: true, mode: 0o700 });
+ this.initLogFile();
+ }
+
+ private getTodaysMidnight() {
+ const now = new Date();
+ return new Date(now.getFullYear(), now.getMonth(), now.getDate());
+ }
+
+ private async cleanupOldLogFiles() {
+ try {
+ let retentionDays = LOGGING_DEFAULT_RETENTION_DAYS;
+ const customRetentionDays = config.Logging.retentionDays;
+ if (customRetentionDays > 0) {
+ retentionDays = customRetentionDays;
+ } else if (customRetentionDays <= -1) {
+ this.info("Log cleanup: keeping all log files, as specified by configuration.");
+ return;
+ }
+
+ const cutoffDate = new Date();
+ cutoffDate.setDate(cutoffDate.getDate() - retentionDays);
+
+ const files = await fs.promises.readdir(dataDir.LOG_DIR);
+ const logFiles: Array<{ name: string; mtime: Date; path: string }> = [];
+
+ for (const file of files) {
+ if (!/^trilium-\d{4}-\d{2}-\d{2}\.log$/.test(file)) {
+ continue;
+ }
+
+ const filePath = path.join(dataDir.LOG_DIR, file);
+ const resolvedPath = path.resolve(filePath);
+ const resolvedLogDir = path.resolve(dataDir.LOG_DIR);
+ if (!resolvedPath.startsWith(resolvedLogDir + path.sep)) {
+ continue;
+ }
+
+ try {
+ const stats = await fs.promises.stat(filePath);
+ logFiles.push({ name: file, mtime: stats.mtime, path: filePath });
+ } catch {
+ // Skip files we can't stat
+ }
+ }
+
+ logFiles.sort((a, b) => a.mtime.getTime() - b.mtime.getTime());
+
+ if (logFiles.length <= MINIMUM_FILES_TO_KEEP) {
+ return;
+ }
+
+ let deletedCount = 0;
+ for (let i = 0; i < logFiles.length - MINIMUM_FILES_TO_KEEP; i++) {
+ const file = logFiles[i];
+ if (file.mtime < cutoffDate) {
+ try {
+ await fs.promises.unlink(file.path);
+ deletedCount++;
+ } catch {
+ // Log deletion failed, but continue with others
+ }
+ }
+ }
+
+ if (deletedCount > 0) {
+ this.info(`Log cleanup: deleted ${deletedCount} old log files`);
+ }
+ } catch {
+ // Cleanup failed, but don't crash the log rotation
+ }
+ }
+
+ private initLogFile() {
+ this.todaysMidnight = this.getTodaysMidnight();
+
+ const logPath = `${dataDir.LOG_DIR}/trilium-${this.formatDate()}.log`;
+ const isRotating = !!this.logFile;
+
+ if (isRotating) {
+ this.logFile!.end();
+ }
+
+ this.logFile = fs.createWriteStream(logPath, { flags: "a" });
+
+ if (isRotating) {
+ this.cleanupOldLogFiles().catch(() => {
+ // Ignore cleanup errors
+ });
+ }
+ }
+
+ private checkDate(millisSinceMidnight: number) {
+ if (millisSinceMidnight >= DAY) {
+ this.initLogFile();
+ millisSinceMidnight -= DAY;
+ }
+ return millisSinceMidnight;
+ }
+
+ override log(message: string | Error) {
+ const bundleNoteId = cls.get("bundleNoteId");
+ let str = String(message);
+
+ if (bundleNoteId) {
+ str = `[Script ${bundleNoteId}] ${str}`;
+ }
+
+ let millisSinceMidnight = Date.now() - this.todaysMidnight.getTime();
+ millisSinceMidnight = this.checkDate(millisSinceMidnight);
+
+ this.logFile!.write(`${this.formatTime(millisSinceMidnight)} ${str}${EOL}`);
+ console.log(str);
+ }
+
+ override info(message: string | Error) {
+ this.log(message);
+ }
+
+ override error(message: string | Error | unknown) {
+ const str = message instanceof Error ? message.stack || message.message : String(message);
+ this.log(`ERROR: ${str}`);
+ }
+
+ request(req: Request, res: Response, timeMs: number, responseLength: number | string = "?") {
+ for (const bl of requestBlacklist) {
+ if (req.url.startsWith(bl)) {
+ return;
+ }
+ }
+
+ if (req.url.includes(".js.map") || req.url.includes(".css.map")) {
+ return;
+ }
+
+ this.info(`${timeMs >= 10 ? "Slow " : ""}${res.statusCode} ${req.method} ${req.url} with ${responseLength} bytes took ${timeMs}ms`);
+ }
+
+ override getLogContents(): string | null {
+ const fileName = `trilium-${this.formatDate()}.log`;
+ const filePath = path.join(dataDir.LOG_DIR, fileName);
+ try {
+ return fs.readFileSync(filePath, "utf8");
+ } catch {
+ return null;
+ }
+ }
+
+ private pad(num: number) {
+ num = Math.floor(num);
+ return num < 10 ? `0${num}` : num.toString();
+ }
+
+ private padMilli(num: number) {
+ if (num < 10) {
+ return `00${num}`;
+ } else if (num < 100) {
+ return `0${num}`;
+ }
+ return num.toString();
+ }
+
+ private formatTime(millisSinceMidnight: number) {
+ return `${this.pad(millisSinceMidnight / HOUR)}:${this.pad((millisSinceMidnight % HOUR) / MINUTE)}:${this.pad((millisSinceMidnight % MINUTE) / SECOND)}.${this.padMilli(millisSinceMidnight % SECOND)}`;
+ }
+
+ private formatDate() {
+ return `${this.pad(this.todaysMidnight.getFullYear())}-${this.pad(this.todaysMidnight.getMonth() + 1)}-${this.pad(this.todaysMidnight.getDate())}`;
+ }
+}
diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts
index 1905ea7102..1d40fce243 100644
--- a/apps/server/src/main.ts
+++ b/apps/server/src/main.ts
@@ -12,6 +12,7 @@ import ClsHookedExecutionContext from "./cls_provider.js";
import { getIntegrationTestDbPath, loadCoreSchema } from "./core_assets.js";
import NodejsCryptoProvider from "./crypto_provider.js";
import NodejsInAppHelpProvider from "./in_app_help_provider.js";
+import ServerLogService from "./log_provider.js";
import ServerPlatformProvider from "./platform_provider.js";
import dataDirs from "./services/data_dir.js";
import port from "./services/port.js";
@@ -37,6 +38,8 @@ async function startApplication() {
dbProvider.loadFromFile(DOCUMENT_PATH, config.General.readOnly);
}
+ const logService = new ServerLogService();
+
await initializeCore({
dbConfig: {
provider: dbProvider,
@@ -49,12 +52,11 @@ async function startApplication() {
const cls = (await import("./services/cls.js")).default;
const becca_loader = (await import("@triliumnext/core")).becca_loader;
const entity_changes = (await import("./services/entity_changes.js")).default;
- const log = (await import("./services/log")).default;
const entityChangeIds = cls.getAndClearEntityChangeIds();
if (entityChangeIds.length > 0) {
- log.info("Transaction rollback dirtied the becca, forcing reload.");
+ logService.info("Transaction rollback dirtied the becca, forcing reload.");
becca_loader.load();
}
@@ -71,6 +73,7 @@ async function startApplication() {
messaging: new WebSocketMessagingProvider(),
schema: loadCoreSchema(),
platform: new ServerPlatformProvider(),
+ log: logService,
translations: (await import("./services/i18n.js")).initializeTranslationsWithParams,
// demo.zip is a server-owned asset; src/assets is copied to dist/assets
// by the build script, so the same RESOURCE_DIR-relative path works in
diff --git a/apps/server/src/routes/api/backend_log.ts b/apps/server/src/routes/api/backend_log.ts
index 2f056158de..8863011f78 100644
--- a/apps/server/src/routes/api/backend_log.ts
+++ b/apps/server/src/routes/api/backend_log.ts
@@ -1,31 +1,14 @@
"use strict";
-import { readFile } from "fs/promises";
-import { join } from "path";
-import dateUtils from "../../services/date_utils.js";
-import dataDir from "../../services/data_dir.js";
-import log from "../../services/log.js";
+import { getLog } from "@triliumnext/core";
import { t } from "i18next";
-const { LOG_DIR } = dataDir;
-
-async function getBackendLog() {
- const fileName = `trilium-${dateUtils.localNowDate()}.log`;
- try {
- const file = join(LOG_DIR, fileName);
- return await readFile(file, "utf8");
- } catch (e) {
- const isErrorInstance = e instanceof Error;
-
- // most probably the log file does not exist yet - https://github.com/zadam/trilium/issues/1977
- if (isErrorInstance && "code" in e && e.code === "ENOENT") {
- log.error(e);
- return t("backend_log.log-does-not-exist", { fileName });
- }
-
- log.error(isErrorInstance ? e : `Reading the backend log '${fileName}' failed with an unknown error: '${e}'.`);
- return t("backend_log.reading-log-failed", { fileName });
+function getBackendLog() {
+ const contents = getLog().getLogContents();
+ if (contents === null) {
+ return t("backend_log.log-does-not-exist", { fileName: "current log" });
}
+ return contents;
}
export default {
diff --git a/apps/server/src/services/log.ts b/apps/server/src/services/log.ts
index 9abc79a500..9b276c1353 100644
--- a/apps/server/src/services/log.ts
+++ b/apps/server/src/services/log.ts
@@ -1,198 +1,21 @@
-import { getLog } from "@triliumnext/core/src/services/log.js";
+import { getLog } from "@triliumnext/core";
import type { Request, Response } from "express";
-import fs from "fs";
-import { EOL } from "os";
-import path from "path";
+import type ServerLogService from "../log_provider.js";
-import cls from "./cls.js";
-import config, { LOGGING_DEFAULT_RETENTION_DAYS } from "./config.js";
-import dataDir from "./data_dir.js";
-
-fs.mkdirSync(dataDir.LOG_DIR, { recursive: true, mode: 0o700 });
-
-let logFile: fs.WriteStream | undefined;
-
-const SECOND = 1000;
-const MINUTE = 60 * SECOND;
-const HOUR = 60 * MINUTE;
-const DAY = 24 * HOUR;
-
-const MINIMUM_FILES_TO_KEEP = 7;
-
-let todaysMidnight!: Date;
-
-initLogFile();
-
-function getTodaysMidnight() {
- const now = new Date();
-
- return new Date(now.getFullYear(), now.getMonth(), now.getDate());
-}
-
-async function cleanupOldLogFiles() {
- try {
- // Get retention days from environment or options
- let retentionDays = LOGGING_DEFAULT_RETENTION_DAYS;
- const customRetentionDays = config.Logging.retentionDays;
- if (customRetentionDays > 0) {
- retentionDays = customRetentionDays;
- } else if (customRetentionDays <= -1){
- info(`Log cleanup: keeping all log files, as specified by configuration.`);
- return;
- }
-
- const cutoffDate = new Date();
- cutoffDate.setDate(cutoffDate.getDate() - retentionDays);
-
- // Read all log files
- const files = await fs.promises.readdir(dataDir.LOG_DIR);
- const logFiles: Array<{name: string, mtime: Date, path: string}> = [];
-
- for (const file of files) {
- // Security: Only process files matching our log pattern
- if (!/^trilium-\d{4}-\d{2}-\d{2}\.log$/.test(file)) {
- continue;
- }
-
- const filePath = path.join(dataDir.LOG_DIR, file);
-
- // Security: Verify path stays within LOG_DIR
- const resolvedPath = path.resolve(filePath);
- const resolvedLogDir = path.resolve(dataDir.LOG_DIR);
- if (!resolvedPath.startsWith(resolvedLogDir + path.sep)) {
- continue;
- }
-
- try {
- const stats = await fs.promises.stat(filePath);
- logFiles.push({ name: file, mtime: stats.mtime, path: filePath });
- } catch (err) {
- // Skip files we can't stat
- }
- }
-
- // Sort by modification time (oldest first)
- logFiles.sort((a, b) => a.mtime.getTime() - b.mtime.getTime());
-
- // Keep minimum number of files
- if (logFiles.length <= MINIMUM_FILES_TO_KEEP) {
- return;
- }
-
- // Delete old files, keeping minimum
- let deletedCount = 0;
- for (let i = 0; i < logFiles.length - MINIMUM_FILES_TO_KEEP; i++) {
- const file = logFiles[i];
- if (file.mtime < cutoffDate) {
- try {
- await fs.promises.unlink(file.path);
- deletedCount++;
- } catch (err) {
- // Log deletion failed, but continue with others
- }
- }
- }
-
- if (deletedCount > 0) {
- info(`Log cleanup: deleted ${deletedCount} old log files`);
- }
- } catch (err) {
- // Cleanup failed, but don't crash the log rotation
- }
-}
-
-function initLogFile() {
- todaysMidnight = getTodaysMidnight();
-
- const logPath = `${dataDir.LOG_DIR}/trilium-${formatDate()}.log`;
- const isRotating = !!logFile;
-
- if (isRotating) {
- logFile!.end();
- }
-
- logFile = fs.createWriteStream(logPath, { flags: "a" });
-
- // Clean up old log files when rotating to a new file
- if (isRotating) {
- cleanupOldLogFiles().catch(() => {
- // Ignore cleanup errors
- });
- }
-}
-
-function checkDate(millisSinceMidnight: number) {
- if (millisSinceMidnight >= DAY) {
- initLogFile();
-
- millisSinceMidnight -= DAY;
- }
-
- return millisSinceMidnight;
-}
-
-function log(str: string | Error) {
- const bundleNoteId = cls.get("bundleNoteId");
-
- if (bundleNoteId) {
- str = `[Script ${bundleNoteId}] ${str}`;
- }
-
- let millisSinceMidnight = Date.now() - todaysMidnight.getTime();
-
- millisSinceMidnight = checkDate(millisSinceMidnight);
-
- logFile!.write(`${formatTime(millisSinceMidnight)} ${str}${EOL}`);
-
- console.log(str);
+function getServerLog(): ServerLogService {
+ return getLog() as ServerLogService;
}
function info(message: string | Error) {
- getLog().info(message);
+ getServerLog().info(message);
}
function error(message: string | Error | unknown) {
- getLog().error(message);
+ getServerLog().error(message);
}
-const requestBlacklist = ["/app", "/images", "/stylesheets", "/api/recent-notes"];
-
function request(req: Request, res: Response, timeMs: number, responseLength: number | string = "?") {
- for (const bl of requestBlacklist) {
- if (req.url.startsWith(bl)) {
- return;
- }
- }
-
- if (req.url.includes(".js.map") || req.url.includes(".css.map")) {
- return;
- }
-
- info(`${timeMs >= 10 ? "Slow " : "" }${res.statusCode} ${req.method} ${req.url} with ${responseLength} bytes took ${timeMs}ms`);
-}
-
-function pad(num: number) {
- num = Math.floor(num);
-
- return num < 10 ? `0${num}` : num.toString();
-}
-
-function padMilli(num: number) {
- if (num < 10) {
- return `00${num}`;
- } else if (num < 100) {
- return `0${num}`;
- }
- return num.toString();
-
-}
-
-function formatTime(millisSinceMidnight: number) {
- return `${pad(millisSinceMidnight / HOUR)}:${pad((millisSinceMidnight % HOUR) / MINUTE)}:${pad((millisSinceMidnight % MINUTE) / SECOND)}.${padMilli(millisSinceMidnight % SECOND)}`;
-}
-
-function formatDate() {
- return `${pad(todaysMidnight.getFullYear())}-${pad(todaysMidnight.getMonth() + 1)}-${pad(todaysMidnight.getDate())}`;
+ getServerLog().request(req, res, timeMs, responseLength);
}
export default {
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index d0551be776..54fb43efdf 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -1,6 +1,6 @@
import { ExecutionContext, initContext } from "./services/context";
import { CryptoProvider, initCrypto } from "./services/encryption/crypto";
-import { getLog, initLog } from "./services/log";
+import LogService, { getLog, initLog } from "./services/log";
import { initSql } from "./services/sql/index";
import { SqlService, SqlServiceParams } from "./services/sql/sql";
import { initMessaging, MessagingProvider } from "./services/messaging/index";
@@ -13,7 +13,7 @@ import { type ZipProvider, initZipProvider } from "./services/zip_provider";
import { type ZipExportProviderFactory, initZipExportProviderFactory } from "./services/export/zip_export_provider_factory";
import { type InAppHelpProvider, initInAppHelp } from "./services/in_app_help";
-export { getLog } from "./services/log";
+export { default as LogService, getLog } from "./services/log";
export type * from "./services/sql/types";
export * from "./services/sql/index";
export { default as sql_init } from "./services/sql_init";
@@ -121,7 +121,7 @@ export { default as scriptService } from "./services/script";
export { default as BackendScriptApi, type Api as BackendScriptApiInterface } from "./services/backend_script_api";
export * as scheduler from "./services/scheduler";
-export async function initializeCore({ dbConfig, executionContext, crypto, zip, zipExportProviderFactory, translations, messaging, request, schema, extraAppInfo, platform, getDemoArchive, inAppHelp }: {
+export async function initializeCore({ dbConfig, executionContext, crypto, zip, zipExportProviderFactory, translations, messaging, request, schema, extraAppInfo, platform, getDemoArchive, inAppHelp, log }: {
dbConfig: SqlServiceParams,
executionContext: ExecutionContext,
crypto: CryptoProvider,
@@ -138,9 +138,10 @@ export async function initializeCore({ dbConfig, executionContext, crypto, zip,
nodeVersion: string;
dataDirectory: string;
};
+ log?: LogService;
}) {
initPlatform(platform);
- initLog();
+ initLog(log);
await initTranslations(translations);
initCrypto(crypto);
initZipProvider(zip);
diff --git a/packages/trilium-core/src/services/log.ts b/packages/trilium-core/src/services/log.ts
index 2447811c9b..f7550c7d1c 100644
--- a/packages/trilium-core/src/services/log.ts
+++ b/packages/trilium-core/src/services/log.ts
@@ -38,12 +38,21 @@ export default class LogService {
console.log(`\n${top}\n${mid}\n${bot}\n`);
}
+ /**
+ * Returns the current log contents as a string.
+ * Override in platform-specific implementations to return actual log data.
+ * @returns The log contents, or null if not available
+ */
+ getLogContents(): string | null {
+ return null;
+ }
+
}
let log: LogService;
-export function initLog() {
- log = new LogService();
+export function initLog(provider?: LogService) {
+ log = provider ?? new LogService();
}
export function getLog() {