Last active
May 23, 2025 17:50
-
-
Save graffhyrum/9d3e95d62caddf428e86206f260e5a68 to your computer and use it in GitHub Desktop.
A proxy wrapper for services to allow logging functionality for requests, responses, and errors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { file } from 'bun' | |
import { mkdirSync, existsSync } from 'node:fs' | |
import { join } from 'node:path' | |
const logFolder = 'LogFolder' | |
const logFilePath = join(process.cwd(), logFolder, 'proxy.log') | |
// Ensure the log folder exists | |
if (!existsSync(logFolder)) { | |
mkdirSync(logFolder) | |
} | |
const logFile = file(logFilePath) | |
const writer = logFile.writer({ highWaterMark: 1024 * 1024 }) // 1MB buffer | |
async function logToFile(message: string) { | |
writer.write(`${new Date().toISOString()} - ${message}\n`) | |
} | |
// Flush the writer when the process is about to exit | |
process.on('beforeExit', async () => { | |
await writer.flush() | |
writer.end() | |
}) | |
export function wrapWithLogging<T extends object>( | |
client: T, | |
debugEnvVar = 'EnableClientDebugging' | |
): T { | |
const debugEnabled = process.env[debugEnvVar] === 'true' | |
if (!debugEnabled) { | |
// Return client as-is if logging is not enabled | |
return client | |
} | |
return new Proxy<T>(client, { | |
get(target, property, receiver) { | |
const original = Reflect.get(target, property, receiver) | |
if (typeof original === 'function') { | |
return async (...args: any[]) => { | |
const requestLog = `Request: ${String(property)} - Args: ${JSON.stringify(args)}` | |
console.debug(requestLog) | |
await logToFile(requestLog) | |
try { | |
const result = await original.apply(target, args) | |
const responseLog = `Response: ${String(property)} - Result: ${JSON.stringify(result)}` | |
console.debug(responseLog) | |
await logToFile(responseLog) | |
return result | |
} catch (error) { | |
const errorLog = `TestRail Error: ${String(property)} - Args: ${JSON.stringify(args)} - Error: ${error}` | |
console.error(errorLog) | |
await logToFile(errorLog) | |
throw error // Re-throw the error to maintain behavior | |
} | |
} | |
} | |
return original | |
}, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment