ReviewOS

also looking at this

stacks/ts-aax

chore: enhance logging

#55
Merged cab-mikee wants to merge chore/enhance-logging into main
12 files +379 -9
src/utils/logger.tsmodified+63-1
Changes to src/utils/logger.ts
@@ -1,9 +1,16 @@
1import process from 'node:process'
12import { Logger } from '@stacksjs/clarity'
23
4// Determine log level via env (falls back to info). Only allow levels supported by clarity Logger
5const envLevel = (process.env.AAX_LOG_LEVEL || '').toLowerCase()
6const allowedLevels = ['error', 'info', 'debug'] as const
7type AllowedLevel = typeof allowedLevels[number]
8const level: AllowedLevel = (allowedLevels as readonly string[]).includes(envLevel) ? (envLevel as AllowedLevel) : 'info'
9
310// Create a logger instance with a fancy UI
411export const logger: Logger = new Logger('aax', {
512 fancy: true,
6 level: 'info',
13 level,
714 showTags: true,
815})
916
@@ -73,3 +80,58 @@ export function formatTime(ms: number): string {
7380
7481 return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
7582}
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 */
88export 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 */
124export 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}