Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(standalone): introduce backend log handling
Elian Doran24112a9b6f7d
diff --git a/apps/client-standalone/src/lightweight/log_provider.ts b/apps/client-standalone/src/lightweight/log_provider.tsnew file mode 100644index 0000000000..ec50b884bd--- /dev/null+++ b/apps/client-standalone/src/lightweight/log_provider.ts@@ -0,0 +1,144 @@+import { FileBasedLogService, type LogFileInfo } from "@triliumnext/core";++const LOG_DIR_NAME = "logs";+const LOG_FILE_PATTERN = /^trilium-\d{4}-\d{2}-\d{2}\.log$/;+const DEFAULT_RETENTION_DAYS = 7;++/**+ * Standalone log service using OPFS (Origin Private File System).+ * Uses synchronous access handles available in service worker context.+ */+export default class StandaloneLogService extends FileBasedLogService {+ private logDir: FileSystemDirectoryHandle | null = null;+ private currentFile: FileSystemSyncAccessHandle | null = null;+ private currentFileName: string = "";+ private textEncoder = new TextEncoder();+ private textDecoder = new TextDecoder();++ constructor() {+ super();+ }++ // ==================== Abstract Method Implementations ====================++ protected override get eol(): string {+ return "\n";+ }++ protected override async ensureLogDirectory(): Promise<void> {+ const root = await navigator.storage.getDirectory();+ this.logDir = await root.getDirectoryHandle(LOG_DIR_NAME, { create: true });+ }++ protected override async openLogFile(fileName: string): Promise<void> {+ if (!this.logDir) {+ await this.ensureLogDirectory();+ }++ // Close existing file if open+ if (this.currentFile) {+ this.currentFile.close();+ this.currentFile = null;+ }++ const fileHandle = await this.logDir!.getFileHandle(fileName, { create: true });+ this.currentFile = await fileHandle.createSyncAccessHandle();+ this.currentFileName = fileName;++ // Seek to end for appending+ const size = this.currentFile.getSize();+ this.currentFile.truncate(size); // No-op, but ensures we're at the right position+ }++ protected override closeLogFile(): void {+ if (this.currentFile) {+ this.currentFile.close();+ this.currentFile = null;+ this.currentFileName = "";+ }+ }++ protected override writeEntry(entry: string): void {+ if (!this.currentFile) {+ console.log(entry); // Fallback to console if file not ready+ return;+ }++ const data = this.textEncoder.encode(entry);+ const currentSize = this.currentFile.getSize();+ this.currentFile.write(data, { at: currentSize });+ this.currentFile.flush();+ }++ protected override readLogFile(fileName: string): string | null {+ if (!this.logDir) {+ return null;+ }++ try {+ // For the current file, we need to read from the sync handle+ if (fileName === this.currentFileName && this.currentFile) {+ const size = this.currentFile.getSize();+ const buffer = new ArrayBuffer(size);+ const view = new DataView(buffer);+ this.currentFile.read(view, { at: 0 });+ return this.textDecoder.decode(buffer);+ }++ // For other files, we'd need async access - return null for now+ // The current file is what's most commonly needed+ return null;+ } catch {+ return null;+ }+ }++ protected override async listLogFiles(): Promise<LogFileInfo[]> {+ if (!this.logDir) {+ return [];+ }++ const logFiles: LogFileInfo[] = [];++ for await (const [name, handle] of this.logDir.entries()) {+ if (handle.kind !== "file" || !LOG_FILE_PATTERN.test(name)) {+ continue;+ }++ // OPFS doesn't provide mtime directly, so we parse from filename+ const match = name.match(/trilium-(\d{4})-(\d{2})-(\d{2})\.log/);+ if (match) {+ const mtime = new Date(+ parseInt(match[1]),+ parseInt(match[2]) - 1,+ parseInt(match[3])+ );+ logFiles.push({ name, mtime });+ }+ }++ return logFiles;+ }++ protected override async deleteLogFile(fileName: string): Promise<void> {+ if (!this.logDir) {+ return;+ }++ // Don't delete the current file+ if (fileName === this.currentFileName) {+ return;+ }++ try {+ await this.logDir.removeEntry(fileName);+ } catch {+ // File might not exist or be locked+ }+ }++ protected override getRetentionDays(): number {+ // Standalone doesn't have config system, use default+ return DEFAULT_RETENTION_DAYS;+ }+}diff --git a/apps/client-standalone/src/local-server-worker.ts b/apps/client-standalone/src/local-server-worker.tsindex 7e6253a641..a238ee0073 100644--- a/apps/client-standalone/src/local-server-worker.ts+++ b/apps/client-standalone/src/local-server-worker.ts@@ -58,6 +58,7 @@ let BrowserCryptoProvider: typeof import('./lightweight/crypto_provider').defaullet BrowserZipProvider: typeof import('./lightweight/zip_provider').default;let FetchRequestProvider: typeof import('./lightweight/request_provider').default;let StandalonePlatformProvider: typeof import('./lightweight/platform_provider').default;+let StandaloneLogService: typeof import('./lightweight/log_provider').default;let translationProvider: typeof import('./lightweight/translation_provider').default;let createConfiguredRouter: typeof import('./lightweight/browser_routes').createConfiguredRouter;@@ -86,6 +87,7 @@ async function loadModules(): Promise<void> {zipModule,requestModule,platformModule,+ logModule,translationModule,routesModule] = await Promise.all([@@ -96,6 +98,7 @@ async function loadModules(): Promise<void> {import('./lightweight/zip_provider.js'),import('./lightweight/request_provider.js'),import('./lightweight/platform_provider.js'),+ import('./lightweight/log_provider.js'),import('./lightweight/translation_provider.js'),import('./lightweight/browser_routes.js')]);@@ -107,6 +110,7 @@ async function loadModules(): Promise<void> {BrowserZipProvider = zipModule.default;FetchRequestProvider = requestModule.default;StandalonePlatformProvider = platformModule.default;+ StandaloneLogService = logModule.default;translationProvider = translationModule.default;createConfiguredRouter = routesModule.createConfiguredRouter;@@ -153,6 +157,12 @@ async function initialize(): Promise<void> {console.log("[Worker] Loading @triliumnext/core...");const schemaModule = await import("@triliumnext/core/src/assets/schema.sql?raw");coreModule = await import("@triliumnext/core");++ // Initialize log service with OPFS persistence+ const logService = new StandaloneLogService();+ await logService.initialize();+ console.log("[Worker] Log service initialized with OPFS");+await coreModule.initializeCore({executionContext: new BrowserExecutionContext(),crypto: new BrowserCryptoProvider(),@@ -161,6 +171,7 @@ async function initialize(): Promise<void> {messaging: messagingProvider!,request: new FetchRequestProvider(),platform: new StandalonePlatformProvider(queryString),+ log: logService,translations: translationProvider,schema: schemaModule.default,getDemoArchive: async () => {diff --git a/apps/server/src/log_provider.ts b/apps/server/src/log_provider.tsindex 38161f0a4b..d149153c9b 100644--- a/apps/server/src/log_provider.ts+++ b/apps/server/src/log_provider.ts@@ -1,153 +1,115 @@-import { LogService } from "@triliumnext/core";+import { FileBasedLogService, type LogFileInfo } 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 LOG_FILE_PATTERN = /^trilium-\d{4}-\d{2}-\d{2}\.log$/;const requestBlacklist = ["/app", "/images", "/stylesheets", "/api/recent-notes"];-export default class ServerLogService extends LogService {+export default class ServerLogService extends FileBasedLogService {private logFile: fs.WriteStream | undefined;- private todaysMidnight!: Date;constructor() {super();- fs.mkdirSync(dataDir.LOG_DIR, { recursive: true, mode: 0o700 });- this.initLogFile();+ // Server uses sync initialization since Node.js fs operations are sync+ this.ensureLogDirectory();+ this.todaysMidnight = this.getTodaysMidnight();+ this.openLogFile(this.getLogFileName());}- private getTodaysMidnight() {- const now = new Date();- return new Date(now.getFullYear(), now.getMonth(), now.getDate());- }+ // ==================== Abstract Method Implementations ====================- 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;- }+ protected override get eol(): string {+ return EOL;+ }- 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- }- }+ protected override ensureLogDirectory(): void {+ fs.mkdirSync(dataDir.LOG_DIR, { recursive: true, mode: 0o700 });+ }- logFiles.sort((a, b) => a.mtime.getTime() - b.mtime.getTime());+ protected override openLogFile(fileName: string): void {+ const logPath = path.join(dataDir.LOG_DIR, fileName);+ this.logFile = fs.createWriteStream(logPath, { flags: "a" });+ }- if (logFiles.length <= MINIMUM_FILES_TO_KEEP) {- return;- }+ protected override closeLogFile(): void {+ if (this.logFile) {+ this.logFile.end();+ this.logFile = undefined;+ }+ }- 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- }- }- }+ protected override writeEntry(entry: string): void {+ this.logFile?.write(entry);+ }- if (deletedCount > 0) {- this.info(`Log cleanup: deleted ${deletedCount} old log files`);- }+ protected override readLogFile(fileName: string): string | null {+ const filePath = path.join(dataDir.LOG_DIR, fileName);+ try {+ return fs.readFileSync(filePath, "utf8");} catch {- // Cleanup failed, but don't crash the log rotation+ return null;}}- private initLogFile() {- this.todaysMidnight = this.getTodaysMidnight();+ protected override async listLogFiles(): Promise<LogFileInfo[]> {+ const files = await fs.promises.readdir(dataDir.LOG_DIR);+ const logFiles: LogFileInfo[] = [];- const logPath = `${dataDir.LOG_DIR}/trilium-${this.formatDate()}.log`;- const isRotating = !!this.logFile;+ for (const file of files) {+ if (!LOG_FILE_PATTERN.test(file)) {+ continue;+ }- if (isRotating) {- this.logFile!.end();- }+ const filePath = path.join(dataDir.LOG_DIR, file);- this.logFile = fs.createWriteStream(logPath, { flags: "a" });+ // 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;+ }- if (isRotating) {- this.cleanupOldLogFiles().catch(() => {- // Ignore cleanup errors- });+ try {+ const stats = await fs.promises.stat(filePath);+ logFiles.push({ name: file, mtime: stats.mtime });+ } catch {+ // Skip files we can't stat+ }}- }- private checkDate(millisSinceMidnight: number) {- if (millisSinceMidnight >= DAY) {- this.initLogFile();- millisSinceMidnight -= DAY;- }- return millisSinceMidnight;+ return logFiles;}- override log(message: string | Error) {- const bundleNoteId = cls.get("bundleNoteId");- let str = String(message);+ protected override async deleteLogFile(fileName: string): Promise<void> {+ const filePath = path.join(dataDir.LOG_DIR, fileName);- if (bundleNoteId) {- str = `[Script ${bundleNoteId}] ${str}`;+ // 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)) {+ return;}- let millisSinceMidnight = Date.now() - this.todaysMidnight.getTime();- millisSinceMidnight = this.checkDate(millisSinceMidnight);-- this.logFile!.write(`${this.formatTime(millisSinceMidnight)} ${str}${EOL}`);- console.log(str);+ await fs.promises.unlink(filePath);}- override info(message: string | Error) {- this.log(message);+ protected override getRetentionDays(): number {+ const customRetentionDays = config.Logging.retentionDays;+ if (customRetentionDays !== undefined && customRetentionDays !== 0) {+ return customRetentionDays;+ }+ return LOGGING_DEFAULT_RETENTION_DAYS;}- override error(message: string | Error | unknown) {- const str = message instanceof Error ? message.stack || message.message : String(message);- this.log(`ERROR: ${str}`);- }+ // ==================== Server-Specific Methods ====================- request(req: Request, res: Response, timeMs: number, responseLength: number | string = "?") {+ request(req: Request, res: Response, timeMs: number, responseLength: number | string = "?"): void {for (const bl of requestBlacklist) {if (req.url.startsWith(bl)) {return;@@ -160,36 +122,4 @@ export default class ServerLogService extends LogService {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/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 54fb43efdf..f2e380bd9c 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -14,6 +14,7 @@ import { type ZipExportProviderFactory, initZipExportProviderFactory } from "./simport { type InAppHelpProvider, initInAppHelp } from "./services/in_app_help";export { default as LogService, getLog } from "./services/log";+export { default as FileBasedLogService, type LogFileInfo } from "./services/file_based_log";export type * from "./services/sql/types";export * from "./services/sql/index";export { default as sql_init } from "./services/sql_init";diff --git a/packages/trilium-core/src/services/file_based_log.ts b/packages/trilium-core/src/services/file_based_log.tsnew file mode 100644index 0000000000..8440a27836--- /dev/null+++ b/packages/trilium-core/src/services/file_based_log.ts@@ -0,0 +1,212 @@+import LogService from "./log.js";+import { getContext } from "./context.js";++const SECOND = 1000;+const MINUTE = 60 * SECOND;+const HOUR = 60 * MINUTE;+const DAY = 24 * HOUR;++const MINIMUM_FILES_TO_KEEP = 7;+const DEFAULT_RETENTION_DAYS = 7;++export interface LogFileInfo {+ name: string;+ mtime: Date;+}++/**+ * Abstract base class for file-based logging implementations.+ * Provides shared logic for log rotation, cleanup, and formatting.+ * Platform-specific implementations (Node.js fs, OPFS) extend this class.+ */+export default abstract class FileBasedLogService extends LogService {+ protected todaysMidnight!: Date;+ private isInitialized = false;++ constructor() {+ super();+ }++ /**+ * Initialize the log service. Must be called before logging.+ * Separated from constructor to allow async initialization in some platforms.+ * For sync platforms (Node.js), call the methods directly in the constructor.+ */+ async initialize(): Promise<void> {+ if (this.isInitialized) return;+ await this.ensureLogDirectory();+ this.todaysMidnight = this.getTodaysMidnight();+ await this.openLogFile(this.getLogFileName());+ this.isInitialized = true;+ }++ // ==================== Abstract Methods ====================++ /** Line ending character(s) for this platform */+ protected abstract get eol(): string;++ /** Ensure the log directory exists */+ protected abstract ensureLogDirectory(): Promise<void> | void;++ /** Open a log file for appending */+ protected abstract openLogFile(fileName: string): Promise<void> | void;++ /** Close the current log file */+ protected abstract closeLogFile(): Promise<void> | void;++ /** Write an entry to the current log file */+ protected abstract writeEntry(entry: string): void;++ /** Read the contents of a log file */+ protected abstract readLogFile(fileName: string): string | null;++ /** List all log files with their modification times */+ protected abstract listLogFiles(): Promise<LogFileInfo[]>;++ /** Delete a log file by name */+ protected abstract deleteLogFile(fileName: string): Promise<void>;++ /** Get the configured retention days (-1 = keep all, 0 = use default) */+ protected abstract getRetentionDays(): number;++ // ==================== Shared Implementation ====================++ protected getTodaysMidnight(): Date {+ const now = new Date();+ return new Date(now.getFullYear(), now.getMonth(), now.getDate());+ }++ protected getLogFileName(): string {+ return `trilium-${this.formatDate()}.log`;+ }++ protected async rotateLogFile(): Promise<void> {+ await this.closeLogFile();+ this.todaysMidnight = this.getTodaysMidnight();+ await this.openLogFile(this.getLogFileName());++ // Trigger cleanup asynchronously+ this.cleanupOldLogFiles().catch(() => {+ // Ignore cleanup errors+ });+ }++ protected checkDateAndRotate(millisSinceMidnight: number): number {+ if (millisSinceMidnight >= DAY) {+ // Trigger rotation asynchronously to avoid blocking+ this.rotateLogFile().catch(() => {});+ return millisSinceMidnight - DAY;+ }+ return millisSinceMidnight;+ }++ protected async cleanupOldLogFiles(): Promise<void> {+ try {+ let retentionDays = this.getRetentionDays();++ if (retentionDays <= -1) {+ this.info("Log cleanup: keeping all log files, as specified by configuration.");+ return;+ }++ if (retentionDays === 0) {+ retentionDays = DEFAULT_RETENTION_DAYS;+ }++ const cutoffDate = new Date();+ cutoffDate.setDate(cutoffDate.getDate() - retentionDays);++ const logFiles = await this.listLogFiles();++ // Sort by modification time (oldest first)+ 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 this.deleteLogFile(file.name);+ 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+ }+ }++ protected getScriptContext(): string | undefined {+ try {+ return getContext().get("bundleNoteId");+ } catch {+ // Context not initialized yet+ return undefined;+ }+ }++ override log(message: string | Error): void {+ const bundleNoteId = this.getScriptContext();+ let str = String(message);++ if (bundleNoteId) {+ str = `[Script ${bundleNoteId}] ${str}`;+ }++ let millisSinceMidnight = Date.now() - this.todaysMidnight.getTime();+ millisSinceMidnight = this.checkDateAndRotate(millisSinceMidnight);++ const entry = `${this.formatTime(millisSinceMidnight)} ${str}${this.eol}`;+ this.writeEntry(entry);+ console.log(str);+ }++ override info(message: string | Error): void {+ this.log(message);+ }++ override error(message: string | Error | unknown): void {+ const str = message instanceof Error+ ? message.stack || message.message+ : String(message);+ this.log(`ERROR: ${str}`);+ }++ override getLogContents(): string | null {+ return this.readLogFile(this.getLogFileName());+ }++ // ==================== Formatting Helpers ====================++ protected pad(num: number): string {+ num = Math.floor(num);+ return num < 10 ? `0${num}` : num.toString();+ }++ protected padMilli(num: number): string {+ if (num < 10) {+ return `00${num}`;+ } else if (num < 100) {+ return `0${num}`;+ }+ return num.toString();+ }++ protected formatTime(millisSinceMidnight: number): string {+ return `${this.pad(millisSinceMidnight / HOUR)}:${this.pad((millisSinceMidnight % HOUR) / MINUTE)}:${this.pad((millisSinceMidnight % MINUTE) / SECOND)}.${this.padMilli(millisSinceMidnight % SECOND)}`;+ }++ protected formatDate(): string {+ return `${this.pad(this.todaysMidnight.getFullYear())}-${this.pad(this.todaysMidnight.getMonth() + 1)}-${this.pad(this.todaysMidnight.getDate())}`;+ }+}