please analyze this logging module for an obsidian plugin:
import { normalizePath, TFile, TFolder, type Vault } from "obsidian";
import { handleFileSystemError } from "./fileUtils";
function getFormattedDate(): string {
const date = new Date();
return date.toISOString()
.replace(/[:.]/g, "-") // Replace colons and periods with hyphens
.replace("T", "_"); // Replace the 'T' in ISO format with an underscore
}
constructor(vault: Vault, logDir: string) {
this.vault = vault;
this.logDir = normalizePath(logDir);
}
public async initialize(cleanupOptions?: {
enabled: boolean;
maxAgeDays?: number;
maxFiles?: number;
}): Promise<void> {
const formattedDate = getFormattedDate();
try {
const folderExists = await this.vault.adapter.exists(this.logDir);
if (!folderExists) {
devLog(
`Log directory ${this.logDir} does not exist. Creating...`,
);
try {
await this.vault.createFolder(this.logDir);
devLog(
`Log directory created successfully: ${this.logDir}`,
);
} catch (createError) {
console.error(
`LogManager: Failed to create log directory ${this.logDir}:`,
createError,
);
throw new Error(
`Failed to create log directory: ${
createError instanceof Error
? createError.message
: String(createError)
}`,
);
}
} else {
devLog(
`Log directory ${this.logDir} exists. Verifying type...`,
);
try {
const folderStat = await this.vault.adapter.stat(
this.logDir,
);
if (!folderStat || folderStat.type !== "folder") {
console.error(
`LogManager: Expected folder at ${this.logDir}, but found type '${folderStat?.type}'. Cannot initialize file logging.`,
);
throw new Error(
`Log path ${this.logDir} exists but is not a folder.`,
);
}
devLog(`Log directory ${this.logDir} verified as folder.`);
if (cleanupOptions?.enabled) {
await this.cleanupOldLogs(
cleanupOptions.maxAgeDays,
cleanupOptions.maxFiles,
);
}
} catch (statError) {
console.error(
`LogManager: Failed to verify log directory type ${this.logDir}:`,
statError,
);
throw new Error(
`Failed to access log directory info: ${
statError instanceof Error
? statError.message
: String(statError)
}`,
);
}
}
const levelName = DebugLevel[currentDebugLevel];
const logFilePath = normalizePath(
`${this.logDir}/koreader-importer_${formattedDate}_${levelName}.md`,
);
const existingLogFile = await this.vault.getAbstractFileByPath(
logFilePath,
);
if (existingLogFile && existingLogFile instanceof TFile) {
this.logFile = existingLogFile;
devLog(`Reusing existing log file: ${logFilePath}`);
} else {
this.logFile = await this.vault.create(
logFilePath,
`[${levelName}] Log initialized at ${
new Date().toISOString()
}\n`,
);
}
} catch (error) {
console.error("Log initialization failed:", error);
handleFileSystemError(
"initializing file logging",
this.logDir,
error,
{
shouldThrow: false,
customNoticeMessage:
"File logging setup failed. Logs will only go to console.",
},
);
}
}
public async write(
message: string,
level: "INFO" | "WARNING" | "ERROR",
): Promise<void> {
if (currentDebugLevel < DebugLevel.INFO) return;
const timestamp = new Date().toISOString();
this.logBuffer.push(`[${timestamp}] [${level}] ${message}`);
if (this.logBuffer.length >= LogManager.MAX_BUFFER_SIZE) {
await this.flush();
} else if (!this.flushTimer) {
this.flushTimer = setTimeout(
() => this.flush(),
LogManager.FLUSH_INTERVAL,
);
}
}
async flush(): Promise<void> {
if (this.isWriting || this.logBuffer.length === 0) return;
this.isWriting = true;
clearTimeout(this.flushTimer);
this.flushTimer = undefined;
const entries = [...this.logBuffer];
this.logBuffer = [];
try {
if (this.logFile) {
await this.vault.modify(
this.logFile,
(await this.vault.read(this.logFile)) + entries.join("\n"),
);
}
} catch (e) {
console.error("Failed to flush log buffer:", e);
this.logBuffer.unshift(...entries);
} finally {
this.isWriting = false;
}
}
private async cleanupOldLogs(
maxAgeDays = 7,
maxFileCount?: number,
): Promise<void> {
const folder = this.vault.getAbstractFileByPath(this.logDir);
if (!folder || !(folder instanceof TFolder)) return;
const now = Date.now();
const cutoffTime = now - (maxAgeDays * 24 * 60 * 60 * 1000);
const logFiles: { file: TFile; mtime: number }[] = [];
// Collect log files
for (const file of folder.children) {
if (
file instanceof TFile &&
file.name.startsWith("koreader-importer_")
) {
const stat = await this.vault.adapter.stat(file.path);
if (stat?.mtime) {
logFiles.push({ file, mtime: stat.mtime });
}
}
}
// Sort by modification time (oldest first)
logFiles.sort((a, b) => a.mtime - b.mtime);
// Delete old files
let i = 0;
while (i < logFiles.length) {
const { file, mtime } = logFiles[i];
if (
mtime < cutoffTime ||
(maxFileCount && logFiles.length - i > maxFileCount)
) {
try {
await this.vault.delete(file);
logFiles.splice(i, 1); // Remove from array
} catch (error) {
console.error(
`Failed to delete log file ${file.name}:`,
error,
);
i++;
}
} else {
break;
}
}
}
public static async promptForCleanup(
vault: Vault,
logDir: string,
): Promise<{
enabled: boolean;
maxAgeDays?: number;
maxFiles?: number;
}> {
return {
enabled: true,
maxAgeDays: 7,
};
}
}
// Global log manager instance
let logManager: LogManager | null = null;
// Update existing logging functions to use the LogManager
export async function initLogging(
vault: Vault,
logFolderPath: string,
cleanupOptions?: {
enabled: boolean;
maxAgeDays?: number;
maxFiles?: number;
},
): Promise {
if (currentDebugLevel < DebugLevel.INFO) return "";
code
logManager = new LogManager(vault, logFolderPath);
await logManager.initialize(cleanupOptions);
return logFolderPath;
}
export async function closeLogging(): Promise {
if (logManager) {
await logManager.flush(); // Ensure buffer is written before unload
logManager = null; // Release reference
devLog("Logging flushed and closed.");
}
}
The logging system has a multi-layered structure with DebugLevel enum and multiple logging functions
There's a LogManager class handling file logging
The code has some inconsistencies in logging levels and error handling
Issues to Address:
Logging Levels:
The DebugLevel enum has 4 levels but the logging functions don't fully utilize them
The devWarn function checks for >= WARNING but devError checks for >= ERROR (should be consistent)
Error Handling:
Error handling is inconsistent (some use try/catch, some don't)
Some error messages are not properly formatted
Code Duplication:
Similar logging logic is repeated in multiple functions
Suggested Improvements:
Key Improvements:
Consistent logging level handling
Reduced code duplication
Better error handling
Clearer separation of concerns
More maintainable structure
Additional Recommendations:
Consider using a logging library like winston or loglevel for more features
Add log rotation support in LogManager
Consider adding log level filtering for file vs console output
Add support for structured logging (JSON format)
Assistant
This is a well-structured analysis of the Obsidian plugin logging module. Let me provide a comprehensive evaluation of both the code and the suggestions:
Code Analysis
The logging module shows good architectural decisions but has several areas for improvement:
Strengths:
Separation of concerns: Console logging and file logging are properly separated
Buffered writing: The LogManager uses buffering with flush intervals to optimize file I/O
Log cleanup: Built-in cleanup functionality for old log files
Error resilience: Attempts to handle errors gracefully without crashing
Issues Identified:
Inconsistent Level Checking:
devLog only logs at exactly INFO level (=== DebugLevel.INFO)
devWarn and devError use >= comparisons
This means INFO logs won't show when level is set to WARNING or ERROR, which is counterintuitive
Type Inconsistency:
devWarn accepts string[] while devLog and devError accept unknown[]
All should probably accept unknown[] for consistency
Redundant Code:
formatMessage is called multiple times in each logging function
The pattern args.map(arg => formatMessage(arg)).join(" ") is repeated
Missing Level Validation:
No validation when setting debug levels
The setDebugMode function hardcodes levels instead of being configurable
Resource Management:
The flush timer isn't cleared in closeLogging
No error handling if log file is deleted while the plugin is running
Evaluation of Suggestions
The suggestions are generally sound and address real issues:
Valid Points:
Logging level inconsistency - This is a real bug that should be fixed
Code duplication - The formatting logic is indeed repeated
Error handling inconsistency - Some functions have try/catch, others don't
Additional Considerations:
Performance Impact:
The current buffering strategy is good, but consider adding a maximum buffer time to prevent data loss
File I/O in Obsidian can be slow; the current approach is reasonable
Obsidian-Specific Constraints:
Using external logging libraries (winston, loglevel) might not be ideal for Obsidian plugins due to bundle size and compatibility
The current approach using Obsidian's Vault API is appropriate
Missing Features:
No log file size limits (only count and age)
No way to dynamically change log levels without restarting
No structured metadata (like plugin version, user settings)
Recommended Improvements:
typescript
// Fix level checking consistency
export function devLog(...args: unknown[]): void {
if (currentDebugLevel >= DebugLevel.INFO) { // Changed from ===
const message = formatArgs(args);
console.log(message);
writeLog(message, "INFO");
}
}
// Centralize formatting
function formatArgs(args: unknown[]): string {
return args.map(arg => formatMessage(arg)).join(" ");
}
// Add proper cleanup
export async function closeLogging(): Promise<void> {
if (logManager) {
clearTimeout(logManager.flushTimer); // Need to expose this
await logManager.flush();
logManager = null;
}
}
// Add validation
export function setDebugLevel(level: DebugLevel): void {
if (level in DebugLevel && typeof level === 'number') {
currentDebugLevel = level;
}
}
The analysis correctly identifies the main issues, and the suggestions would improve code quality. However, be cautious about over-engineering for an Obsidian plugin context where simplicity and small bundle size are important.