forked from ericc-ch/copilot-api
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdebug-logger.ts
More file actions
243 lines (218 loc) · 7.02 KB
/
debug-logger.ts
File metadata and controls
243 lines (218 loc) · 7.02 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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import { existsSync, mkdirSync } from "node:fs"
import { writeFile } from "node:fs/promises"
import { join } from "node:path"
import type { GeminiRequest } from "~/routes/generate-content/types"
import type {
ChatCompletionsPayload,
ChatCompletionResponse,
} from "~/services/copilot/create-chat-completions"
interface DebugLogData {
timestamp: string
requestId: string
originalGeminiPayload: GeminiRequest
translatedOpenAIPayload: ChatCompletionsPayload | null
error?: string
processingTime?: number
}
export class DebugLogger {
private static instance: DebugLogger | undefined
private logDir: string
private constructor() {
this.logDir = process.env.DEBUG_LOG_DIR || join(process.cwd(), "debug-logs")
this.ensureLogDir()
}
static getInstance(): DebugLogger {
if (!DebugLogger.instance) {
DebugLogger.instance = new DebugLogger()
}
return DebugLogger.instance
}
private ensureLogDir(): void {
if (!existsSync(this.logDir)) {
mkdirSync(this.logDir, { recursive: true })
}
}
private generateLogFileName(requestId: string): string {
const timestamp = new Date().toISOString().replaceAll(/[:.]/g, "-")
return join(this.logDir, `debug-gemini-${timestamp}-${requestId}.log`)
}
/**
* Redact sensitive data from Gemini request payloads to reduce risk of
* accidental data exposure when DEBUG_GEMINI_REQUESTS is enabled.
*
* Redacted fields:
* - contents[].parts[].text → "[REDACTED]"
* - systemInstruction.parts[].text → "[REDACTED]"
* - functionCall.args → "[REDACTED]"
* - functionResponse.response → "[REDACTED]"
*
* Enable redaction by setting DEBUG_REDACT_SENSITIVE=true
*/
private redactSensitiveData(payload: GeminiRequest): GeminiRequest {
// Skip redaction if not explicitly enabled
if (process.env.DEBUG_REDACT_SENSITIVE !== "true") {
return payload
}
// Deep clone to avoid mutating original
const redacted = structuredClone(payload)
// Redact contents
redacted.contents = redacted.contents.map((content) => ({
...content,
parts: content.parts.map((part) => {
if ("text" in part) {
return { text: "[REDACTED]" }
}
if ("functionCall" in part) {
return {
functionCall: {
name: part.functionCall.name,
args: "[REDACTED]" as unknown as Record<string, unknown>,
},
}
}
if ("functionResponse" in part) {
return {
functionResponse: {
name: part.functionResponse.name,
response: { redacted: true } as Record<string, unknown>,
},
}
}
return part
}),
}))
// Redact system instruction
if (redacted.systemInstruction) {
redacted.systemInstruction = {
...redacted.systemInstruction,
parts: redacted.systemInstruction.parts.map((part) => {
if ("text" in part) {
return { text: "[REDACTED]" }
}
return part
}),
}
}
return redacted
}
async logRequest(data: {
requestId: string
geminiPayload: GeminiRequest
openAIPayload?: ChatCompletionsPayload | null
error?: string
processingTime?: number
}): Promise<void> {
const logData: DebugLogData = {
timestamp: new Date().toISOString(),
requestId: data.requestId,
originalGeminiPayload: this.redactSensitiveData(data.geminiPayload),
translatedOpenAIPayload: data.openAIPayload ?? null,
error: data.error,
processingTime: data.processingTime,
}
const logPath = this.generateLogFileName(data.requestId)
try {
await writeFile(logPath, JSON.stringify(logData, null, 2), "utf8")
console.log(`[DEBUG] Logged request data to: ${logPath}`)
} catch (writeError) {
console.error(`[DEBUG] Failed to write log file ${logPath}:`, writeError)
}
}
// For backward compatibility during development
static async logGeminiRequest(
geminiPayload: GeminiRequest,
openAIPayload?: ChatCompletionsPayload,
error?: string,
): Promise<void> {
const logger = DebugLogger.getInstance()
const requestId = Math.random().toString(36).slice(2, 8)
await logger.logRequest({ requestId, geminiPayload, openAIPayload, error })
}
// Log GitHub Copilot API Response
static async logCopilotResponse(
response: ChatCompletionResponse,
context?: string,
): Promise<void> {
const logger = DebugLogger.getInstance()
const requestId = Math.random().toString(36).slice(2, 8)
const timestamp = new Date().toISOString().replaceAll(/[:.]/g, "-")
const logPath = join(
logger.logDir,
`debug-copilot-response-${timestamp}-${requestId}.log`,
)
const logData = {
timestamp: new Date().toISOString(),
context: context || "GitHub Copilot API Response",
response,
}
try {
await writeFile(logPath, JSON.stringify(logData, null, 2), "utf8")
console.log(`[DEBUG] Logged Copilot response to: ${logPath}`)
} catch (writeError) {
console.error(
`[DEBUG] Failed to write Copilot response log file ${logPath}:`,
writeError,
)
}
}
// Log any object for debugging purposes
static async logDebugData(
data: unknown,
context: string,
filePrefix = "debug-data",
): Promise<void> {
const logger = DebugLogger.getInstance()
const requestId = Math.random().toString(36).slice(2, 8)
const timestamp = new Date().toISOString().replaceAll(/[:.]/g, "-")
const logPath = join(
logger.logDir,
`${filePrefix}-${timestamp}-${requestId}.log`,
)
const logData = {
timestamp: new Date().toISOString(),
context,
data,
}
try {
await writeFile(logPath, JSON.stringify(logData, null, 2), "utf8")
console.log(`[DEBUG] Logged ${context} to: ${logPath}`)
} catch (writeError) {
console.error(
`[DEBUG] Failed to write debug log file ${logPath}:`,
writeError,
)
}
}
// Log original and translated response comparison
static async logResponseComparison(
originalResponse: unknown,
translatedResponse: unknown,
options: { context: string; filePrefix?: string } = {
context: "Response Comparison",
},
): Promise<void> {
const { context, filePrefix = "debug-comparison" } = options
const logger = DebugLogger.getInstance()
const requestId = Math.random().toString(36).slice(2, 8)
const timestamp = new Date().toISOString().replaceAll(/[:.]/g, "-")
const logPath = join(
logger.logDir,
`${filePrefix}-${timestamp}-${requestId}.log`,
)
const logData = {
timestamp: new Date().toISOString(),
context,
originalResponse,
translatedResponse,
}
try {
await writeFile(logPath, JSON.stringify(logData, null, 2), "utf8")
console.log(`[DEBUG] Logged ${context} comparison to: ${logPath}`)
} catch (writeError) {
console.error(
`[DEBUG] Failed to write comparison log file ${logPath}:`,
writeError,
)
}
}
}