-
-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathlogger.ts
More file actions
205 lines (173 loc) · 6.96 KB
/
logger.ts
File metadata and controls
205 lines (173 loc) · 6.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import { writeFile, mkdir } from "fs/promises"
import { join } from "path"
import { existsSync } from "fs"
import { homedir } from "os"
export class Logger {
private logDir: string
public enabled: boolean
constructor(enabled: boolean) {
this.enabled = enabled
const opencodeConfigDir = join(homedir(), ".config", "opencode")
this.logDir = join(opencodeConfigDir, "logs", "dcp")
}
private async ensureLogDir() {
if (!existsSync(this.logDir)) {
await mkdir(this.logDir, { recursive: true })
}
}
private formatData(data?: any): string {
if (!data) return ""
const parts: string[] = []
for (const [key, value] of Object.entries(data)) {
if (value === undefined || value === null) continue
// Format arrays compactly
if (Array.isArray(value)) {
if (value.length === 0) continue
parts.push(
`${key}=[${value.slice(0, 3).join(",")}${value.length > 3 ? `...+${value.length - 3}` : ""}]`,
)
} else if (typeof value === "object") {
const str = JSON.stringify(value)
if (str.length < 50) {
parts.push(`${key}=${str}`)
}
} else {
parts.push(`${key}=${value}`)
}
}
return parts.join(" ")
}
private getCallerFile(skipFrames: number = 3): string {
const originalPrepareStackTrace = Error.prepareStackTrace
try {
const err = new Error()
Error.prepareStackTrace = (_, stack) => stack
const stack = err.stack as unknown as NodeJS.CallSite[]
Error.prepareStackTrace = originalPrepareStackTrace
// Skip specified number of frames to get to actual caller
for (let i = skipFrames; i < stack.length; i++) {
const filename = stack[i]?.getFileName()
if (filename && !filename.includes("/logger.")) {
// Extract just the filename without path and extension
const match = filename.match(/([^/\\]+)\.[tj]s$/)
return match ? match[1] : filename
}
}
return "unknown"
} catch {
return "unknown"
}
}
private async write(level: string, component: string, message: string, data?: any) {
if (!this.enabled) return
try {
await this.ensureLogDir()
const timestamp = new Date().toISOString()
const dataStr = this.formatData(data)
const logLine = `${timestamp} ${level.padEnd(5)} ${component}: ${message}${dataStr ? " | " + dataStr : ""}\n`
const dailyLogDir = join(this.logDir, "daily")
if (!existsSync(dailyLogDir)) {
await mkdir(dailyLogDir, { recursive: true })
}
const logFile = join(dailyLogDir, `${new Date().toISOString().split("T")[0]}.log`)
await writeFile(logFile, logLine, { flag: "a" })
} catch (error) {}
}
info(message: string, data?: any) {
const component = this.getCallerFile(2)
return this.write("INFO", component, message, data)
}
debug(message: string, data?: any) {
const component = this.getCallerFile(2)
return this.write("DEBUG", component, message, data)
}
warn(message: string, data?: any) {
const component = this.getCallerFile(2)
return this.write("WARN", component, message, data)
}
error(message: string, data?: any) {
const component = this.getCallerFile(2)
return this.write("ERROR", component, message, data)
}
/**
* Strips unnecessary metadata from messages for cleaner debug logs.
*
* Removed:
* - All IDs (id, sessionID, messageID, parentID, callID on parts)
* - summary, path, cost, model, agent, mode, finish, providerID, modelID
* - step-start and step-finish parts entirely
* - snapshot fields
* - ignored text parts
*
* Kept:
* - role, time (created only), tokens (input, output, reasoning, cache)
* - text, reasoning, tool parts with content
* - tool calls with: tool, callID, input, output
*/
private minimizeForDebug(messages: any[]): any[] {
return messages.map((msg) => {
const minimized: any = {
role: msg.info?.role,
}
if (msg.info?.time?.created) {
minimized.time = msg.info.time.created
}
if (msg.info?.tokens) {
minimized.tokens = {
input: msg.info.tokens.input,
output: msg.info.tokens.output,
reasoning: msg.info.tokens.reasoning,
cache: msg.info.tokens.cache,
}
}
if (msg.parts) {
minimized.parts = msg.parts
.map((part: any) => {
if (part.type === "step-start" || part.type === "step-finish") {
return null
}
if (part.type === "text") {
if (part.ignored) return null
return { type: "text", text: part.text }
}
if (part.type === "reasoning") {
return {
type: "reasoning",
text: part.text,
}
}
if (part.type === "tool") {
const toolPart: any = {
type: "tool",
tool: part.tool,
callID: part.callID,
}
if (part.state?.input) {
toolPart.input = part.state.input
}
if (part.state?.output) {
toolPart.output = part.state.output
}
return toolPart
}
return null
})
.filter(Boolean)
}
return minimized
})
}
async saveContext(sessionId: string, messages: any[]) {
if (!this.enabled) return
try {
const contextDir = join(this.logDir, "context", sessionId)
if (!existsSync(contextDir)) {
await mkdir(contextDir, { recursive: true })
}
const minimized = this.minimizeForDebug(messages)
const timestamp = new Date().toISOString().replace(/[:.]/g, "-")
const contextFile = join(contextDir, `${timestamp}.json`)
await writeFile(contextFile, JSON.stringify(minimized, null, 2))
} catch (error) {}
}
}