diff --git a/index.ts b/index.ts index 6bef488..29beaee 100644 --- a/index.ts +++ b/index.ts @@ -4,7 +4,7 @@ import path from "path" import { MatrixBotClient } from "./matrix-client.js" import { SessionManager } from "./session-manager.js" import { loadConfig } from "./config-loader.js" -import { log, logError } from "./logger.js" +import { setAppLog, log, logError } from "./logger.js" // ============================================================================= // Plugin data directory — uses the same default as matrix-client @@ -296,6 +296,11 @@ async function v2Setup(ctx: any) { : path.join(os.homedir(), ".local", "share", "opencode-matrix-bot", "plugin-data") ensureDataDir(dataDir) + // Try to use OpenCode's logging API + if (ctx?.app?.log) { + setAppLog(ctx.app.log.bind(ctx.app)) + } + try { const { options } = await loadConfig(ctx.options) return await runPlugin(ctx, options, dataDir) diff --git a/logger.ts b/logger.ts index 23088bf..edb9e02 100644 --- a/logger.ts +++ b/logger.ts @@ -5,20 +5,62 @@ import path from "path" const LOG_DIR = path.join(os.homedir(), ".opencode-matrix-plugin") const LOG_FILE = path.join(LOG_DIR, "plugin.log") +let appLog: ((data: any) => Promise) | null = null + +export function setAppLog(fn: (data: any) => Promise): void { + appLog = fn +} + export function log(message: string): void { - try { - fs.mkdirSync(LOG_DIR, { recursive: true }) - fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] [matrix-plugin] ${message}\n`) - } catch { - // silent + // Try OpenCode's logging API first + if (appLog) { + appLog({ + service: "matrix-plugin", + level: "info", + message, + }).catch(() => { + // Fallback to file logging + try { + fs.mkdirSync(LOG_DIR, { recursive: true }) + fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] [matrix-plugin] ${message}\n`) + } catch { + // silent + } + }) + } else { + // No app log available, use file logging + try { + fs.mkdirSync(LOG_DIR, { recursive: true }) + fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] [matrix-plugin] ${message}\n`) + } catch { + // silent + } } } export function logError(message: string): void { - try { - fs.mkdirSync(LOG_DIR, { recursive: true }) - fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] [matrix-plugin] ERROR: ${message}\n`) - } catch { - // silent + // Try OpenCode's logging API first + if (appLog) { + appLog({ + service: "matrix-plugin", + level: "error", + message, + }).catch(() => { + // Fallback to file logging + try { + fs.mkdirSync(LOG_DIR, { recursive: true }) + fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] [matrix-plugin] ERROR: ${message}\n`) + } catch { + // silent + } + }) + } else { + // No app log available, use file logging + try { + fs.mkdirSync(LOG_DIR, { recursive: true }) + fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] [matrix-plugin] ERROR: ${message}\n`) + } catch { + // silent + } } }