also looking at this
chore: enhance logging
#55
12 files
+379
-9
| @@ -1,9 +1,16 @@ | ||
| 1 | import process from 'node:process' | |
| 1 | 2 | import { Logger } from '@stacksjs/clarity' |
| 2 | 3 | |
| 4 | // Determine log level via env (falls back to info). Only allow levels supported by clarity Logger | |
| 5 | const envLevel = (process.env.AAX_LOG_LEVEL || '').toLowerCase() | |
| 6 | const allowedLevels = ['error', 'info', 'debug'] as const | |
| 7 | type AllowedLevel = typeof allowedLevels[number] | |
| 8 | const level: AllowedLevel = (allowedLevels as readonly string[]).includes(envLevel) ? (envLevel as AllowedLevel) : 'info' | |
| 9 | ||
| 3 | 10 | // Create a logger instance with a fancy UI |
| 4 | 11 | export const logger: Logger = new Logger('aax', { |
| 5 | 12 | fancy: true, |
| 6 | level: 'info', | |
| 13 | level, | |
| 7 | 14 | showTags: true, |
| 8 | 15 | }) |
| 9 | 16 | |
| @@ -73,3 +80,58 @@ export function formatTime(ms: number): string { | ||
| 73 | 80 | |
| 74 | 81 | return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}` |
| 75 | 82 | } |
| 83 | ||
| 84 | /** | |
| 85 | * Report an error with optional heading, details and hints. | |
| 86 | * In debug mode (AAX_LOG_LEVEL=debug or AAX_DEBUG=1), also prints stack traces when available. | |
| 87 | */ | |
| 88 | export function reportError( | |
| 89 | error: unknown, | |
| 90 | options?: { | |
| 91 | heading?: string | |
| 92 | details?: string | |
| 93 | hints?: string[] | |
| 94 | }, | |
| 95 | ): void { | |
| 96 | const isDebug = level === 'debug' || process.env.AAX_DEBUG === '1' | |
| 97 | ||
| 98 | const heading = options?.heading | |
| 99 | const details = options?.details | |
| 100 | const hints = options?.hints || [] | |
| 101 | ||
| 102 | // Extract message/stack from various error shapes | |
| 103 | const errObj = normalizeError(error) | |
| 104 | ||
| 105 | if (heading) | |
| 106 | logger.error(heading) | |
| 107 | ||
| 108 | if (errObj.message) | |
| 109 | logger.error(errObj.message) | |
| 110 | ||
| 111 | if (details) | |
| 112 | logger.warn(details) | |
| 113 | ||
| 114 | for (const hint of hints) | |
| 115 | logger.warn(`Hint: ${hint}`) | |
| 116 | ||
| 117 | if (isDebug && errObj.stack) | |
| 118 | logger.debug(errObj.stack) | |
| 119 | } | |
| 120 | ||
| 121 | /** | |
| 122 | * Normalize unknown errors to a consistent shape. | |
| 123 | */ | |
| 124 | export function normalizeError(error: unknown): { message: string; stack?: string } { | |
| 125 | if (error instanceof Error) { | |
| 126 | return { message: error.message, stack: error.stack } | |
| 127 | } | |
| 128 | if (typeof error === 'string') { | |
| 129 | return { message: error } | |
| 130 | } | |
| 131 | try { | |
| 132 | return { message: JSON.stringify(error) } | |
| 133 | } | |
| 134 | catch { | |
| 135 | return { message: String(error) } | |
| 136 | } | |
| 137 | } | |