File
Blob: src/worker/logger.ts
| 1 | type LogLevel = "info" | "warn" | "error"; |
| 2 | type LogContext = Record<string, unknown>; |
| 3 | |
| 4 | function normalizeContext(context?: LogContext): LogContext | undefined { |
| 5 | if (!context) { |
| 6 | return undefined; |
| 7 | } |
| 8 | |
| 9 | return Object.fromEntries(Object.entries(context).filter(([, value]) => value !== undefined)); |
| 10 | } |
| 11 | |
| 12 | function write(level: LogLevel, scope: string, event: string, message: string, context?: LogContext) { |
| 13 | const entry = { |
| 14 | timestamp: new Date().toISOString(), |
| 15 | level, |
| 16 | scope, |
| 17 | event, |
| 18 | message, |
| 19 | ...normalizeContext(context), |
| 20 | }; |
| 21 | |
| 22 | const payload = JSON.stringify(entry); |
| 23 | |
| 24 | if (level === "error") { |
| 25 | console.error(payload); |
| 26 | return; |
| 27 | } |
| 28 | |
| 29 | if (level === "warn") { |
| 30 | console.warn(payload); |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | console.log(payload); |
| 35 | } |
| 36 | |
| 37 | export function errorContext(error: unknown) { |
| 38 | if (error instanceof Error) { |
| 39 | return { |
| 40 | errorName: error.name, |
| 41 | errorMessage: error.message, |
| 42 | }; |
| 43 | } |
| 44 | |
| 45 | return { |
| 46 | errorMessage: String(error), |
| 47 | }; |
| 48 | } |
| 49 | |
| 50 | export function createLogger(scope: string) { |
| 51 | return { |
| 52 | info(event: string, message: string, context?: LogContext) { |
| 53 | write("info", scope, event, message, context); |
| 54 | }, |
| 55 | warn(event: string, message: string, context?: LogContext) { |
| 56 | write("warn", scope, event, message, context); |
| 57 | }, |
| 58 | error(event: string, message: string, context?: LogContext) { |
| 59 | write("error", scope, event, message, context); |
| 60 | }, |
| 61 | }; |
| 62 | } |