Skip to content

Commit 508cc2e

Browse files
committed
Enhance logger with AI context saving and reorganized log structure
- Add saveWrappedContext() method to save AI message context for debugging - Reorganize daily logs into daily/ subdirectory for better organization - Add file counter to prevent filename collisions - Make enabled property public for external access
1 parent d916429 commit 508cc2e

File tree

1 file changed

+50
-2
lines changed

1 file changed

+50
-2
lines changed

lib/logger.ts

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ import { homedir } from "os"
66

77
export class Logger {
88
private logDir: string
9-
private enabled: boolean
9+
public enabled: boolean
10+
private fileCounter: number = 0 // Counter to prevent filename collisions
1011

1112
constructor(enabled: boolean) {
1213
this.enabled = enabled
@@ -37,7 +38,12 @@ export class Logger {
3738
...(data && { data })
3839
}
3940

40-
const logFile = join(this.logDir, `${new Date().toISOString().split('T')[0]}.log`)
41+
const dailyLogDir = join(this.logDir, "daily")
42+
if (!existsSync(dailyLogDir)) {
43+
await mkdir(dailyLogDir, { recursive: true })
44+
}
45+
46+
const logFile = join(dailyLogDir, `${new Date().toISOString().split('T')[0]}.log`)
4147
const logLine = JSON.stringify(logEntry) + "\n"
4248

4349
await writeFile(logFile, logLine, { flag: "a" })
@@ -61,4 +67,46 @@ export class Logger {
6167
error(component: string, message: string, data?: any) {
6268
return this.write("ERROR", component, message, data)
6369
}
70+
71+
/**
72+
* Saves AI context to a dedicated directory for debugging
73+
* Each call creates a new timestamped file in ~/.config/opencode/logs/dcp/ai-context/
74+
* Only writes if debug is enabled
75+
*/
76+
async saveWrappedContext(sessionID: string, messages: any[], metadata: any) {
77+
if (!this.enabled) return
78+
79+
try {
80+
await this.ensureLogDir()
81+
82+
const aiContextDir = join(this.logDir, "ai-context")
83+
if (!existsSync(aiContextDir)) {
84+
await mkdir(aiContextDir, { recursive: true })
85+
}
86+
87+
const timestamp = new Date().toISOString().replace(/:/g, '-').replace(/\./g, '-')
88+
// Add counter to prevent filename collisions when multiple requests happen in same millisecond
89+
const counter = (this.fileCounter++).toString().padStart(3, '0')
90+
const filename = `${timestamp}_${counter}_${sessionID.substring(0, 15)}.json`
91+
const filepath = join(aiContextDir, filename)
92+
93+
const content = {
94+
timestamp: new Date().toISOString(),
95+
sessionID,
96+
metadata,
97+
messages
98+
}
99+
100+
await writeFile(filepath, JSON.stringify(content, null, 2))
101+
102+
// Log that we saved it
103+
await this.debug("logger", "Saved AI context", {
104+
sessionID,
105+
filepath,
106+
messageCount: messages.length
107+
})
108+
} catch (error) {
109+
// Silently fail - don't break the plugin if logging fails
110+
}
111+
}
64112
}

0 commit comments

Comments
 (0)