|
| 1 | +import consola from "consola" |
| 2 | +import fs from "node:fs/promises" |
| 3 | +import path from "pathe" |
| 4 | + |
| 5 | +export interface LoggerOptions { |
| 6 | + enabled: boolean |
| 7 | + filePath?: string |
| 8 | +} |
| 9 | + |
| 10 | +export const logger = { |
| 11 | + options: { |
| 12 | + enabled: false, |
| 13 | + filePath: undefined, |
| 14 | + } as LoggerOptions, |
| 15 | + |
| 16 | + async initialize(filePath?: string): Promise<void> { |
| 17 | + if (!filePath) { |
| 18 | + this.options.enabled = false |
| 19 | + return |
| 20 | + } |
| 21 | + |
| 22 | + try { |
| 23 | + // Ensure the directory exists |
| 24 | + await fs.mkdir(path.dirname(filePath), { recursive: true }) |
| 25 | + |
| 26 | + // Initialize the log file with a header |
| 27 | + const timestamp = new Date().toISOString() |
| 28 | + await fs.writeFile( |
| 29 | + filePath, |
| 30 | + `# API Request/Response Log\n# Started: ${timestamp}\n\n`, |
| 31 | + { flag: "w" }, |
| 32 | + ) |
| 33 | + |
| 34 | + this.options.enabled = true |
| 35 | + this.options.filePath = filePath |
| 36 | + consola.success(`Request logging enabled to: ${filePath}`) |
| 37 | + } catch (error) { |
| 38 | + consola.error(`Failed to initialize log file`, error) |
| 39 | + this.options.enabled = false |
| 40 | + } |
| 41 | + }, |
| 42 | + |
| 43 | + async logRequest( |
| 44 | + endpoint: string, |
| 45 | + method: string, |
| 46 | + payload: unknown, |
| 47 | + ): Promise<void> { |
| 48 | + if (!this.options.enabled || !this.options.filePath) return |
| 49 | + |
| 50 | + const timestamp = new Date().toISOString() |
| 51 | + const logEntry = [ |
| 52 | + `## Request - ${timestamp}`, |
| 53 | + `Endpoint: ${endpoint}`, |
| 54 | + `Method: ${method}`, |
| 55 | + `Payload:`, |
| 56 | + `\`\`\`json`, |
| 57 | + JSON.stringify(payload, null, 2), |
| 58 | + `\`\`\``, |
| 59 | + `\n`, |
| 60 | + ].join("\n") |
| 61 | + |
| 62 | + try { |
| 63 | + await fs.appendFile(this.options.filePath, logEntry) |
| 64 | + } catch (error) { |
| 65 | + consola.error(`Failed to write to log file`, error) |
| 66 | + } |
| 67 | + }, |
| 68 | + |
| 69 | + async logResponse(endpoint: string, response: unknown): Promise<void> { |
| 70 | + if (!this.options.enabled || !this.options.filePath) return |
| 71 | + |
| 72 | + const timestamp = new Date().toISOString() |
| 73 | + const logEntry = [ |
| 74 | + `## Response - ${timestamp}`, |
| 75 | + `Endpoint: ${endpoint}`, |
| 76 | + `Response:`, |
| 77 | + `\`\`\`json`, |
| 78 | + JSON.stringify(response, null, 2), |
| 79 | + `\`\`\``, |
| 80 | + `\n`, |
| 81 | + ].join("\n") |
| 82 | + |
| 83 | + try { |
| 84 | + await fs.appendFile(this.options.filePath, logEntry) |
| 85 | + } catch (error) { |
| 86 | + consola.error(`Failed to write to log file`, error) |
| 87 | + } |
| 88 | + }, |
| 89 | +} |
0 commit comments