| 1 | import { appLogger } from "@/lib/observability/logger"; |
| 2 | |
| 3 | type SpanAttributes = Record<string, string | number | boolean | undefined>; |
| 4 | |
| 5 | class ConsoleSpan { |
| 6 | private readonly startedAt = Date.now(); |
| 7 | private attributes: SpanAttributes; |
| 8 | |
| 9 | constructor( |
| 10 | private readonly name: string, |
| 11 | initialAttributes?: SpanAttributes, |
| 12 | ) { |
| 13 | this.attributes = { ...initialAttributes }; |
| 14 | appLogger.child("server").info("Span started", { |
| 15 | spanName: this.name, |
| 16 | attributes: this.attributes, |
| 17 | }); |
| 18 | } |
| 19 | |
| 20 | annotate(attributes: SpanAttributes) { |
| 21 | this.attributes = { |
| 22 | ...this.attributes, |
| 23 | ...attributes, |
| 24 | }; |
| 25 | } |
| 26 | |
| 27 | event(name: string, attributes?: SpanAttributes) { |
| 28 | appLogger.child("server").info(name, { |
| 29 | spanName: this.name, |
| 30 | attributes: { |
| 31 | ...this.attributes, |
| 32 | ...attributes, |
| 33 | }, |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | error(error: unknown) { |
| 38 | appLogger.child("server").error("Span failed", error, { |
| 39 | spanName: this.name, |
| 40 | attributes: this.attributes, |
| 41 | }); |
| 42 | } |
| 43 | |
| 44 | end() { |
| 45 | appLogger.child("server").info("Span ended", { |
| 46 | spanName: this.name, |
| 47 | durationMs: Date.now() - this.startedAt, |
| 48 | attributes: this.attributes, |
| 49 | }); |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | export const logger = { |
| 54 | info(message: string, attributes?: SpanAttributes) { |
| 55 | appLogger.child("server").info(message, attributes); |
| 56 | }, |
| 57 | warn(message: string, attributes?: SpanAttributes) { |
| 58 | appLogger.child("server").warn(message, attributes); |
| 59 | }, |
| 60 | error(message: string, error?: unknown, attributes?: SpanAttributes) { |
| 61 | appLogger.child("server").error(message, error, attributes); |
| 62 | }, |
| 63 | startSpan(name: string, options?: { attributes?: SpanAttributes }) { |
| 64 | return new ConsoleSpan(name, options?.attributes); |
| 65 | }, |
| 66 | }; |
| 67 |