-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathlogging.ts
More file actions
267 lines (241 loc) · 6.01 KB
/
logging.ts
File metadata and controls
267 lines (241 loc) · 6.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// Structured logging utilities for Runt runtime agents
//
// This module provides a clean logging interface that leverages OpenTelemetry
// for structured, observable logging. Configure once at startup, use everywhere.
import {
context,
SpanKind,
SpanStatusCode,
trace,
} from "npm:@opentelemetry/api";
/**
* Log levels in order of severity
*/
export enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
}
/**
* Configuration for the logger
*/
export interface LoggerConfig {
/** Minimum log level to output */
level: LogLevel;
/** Whether to also output to console */
console: boolean;
/** Service name for structured logs */
service: string;
}
/**
* Structured logger that uses OpenTelemetry for observability
*/
class Logger {
private config: LoggerConfig = {
level: LogLevel.INFO,
console: true,
service: "runt-agent",
};
private tracer = trace.getTracer("@runt/lib");
/**
* Configure the logger (call once at startup)
*/
configure(config: Partial<LoggerConfig>): void {
this.config = { ...this.config, ...config };
}
/**
* Get the current configuration
*/
getConfig(): LoggerConfig {
return { ...this.config };
}
getLevel(): LogLevel {
return this.config.level;
}
/**
* Log a debug message
*/
debug(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.DEBUG, message, context);
}
/**
* Log an info message
*/
info(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.INFO, message, context);
}
/**
* Log a warning message
*/
warn(message: string, context?: Record<string, unknown>): void {
this.log(LogLevel.WARN, message, context);
}
/**
* Log an error message
*/
error(
message: string,
error?: Error | unknown,
context?: Record<string, unknown>,
): void {
const errorData = error instanceof Error
? {
error: {
name: error.name,
message: error.message,
stack: error.stack,
},
...context,
}
: { error: String(error), ...context };
this.log(LogLevel.ERROR, message, errorData);
}
/**
* Create a traced operation with automatic logging
*/
trace<T>(
name: string,
operation: () => Promise<T>,
attributes?: Record<string, unknown>,
): Promise<T> {
const span = this.tracer.startSpan(name, {
kind: SpanKind.INTERNAL,
attributes: {
service: this.config.service,
...attributes,
},
});
return context.with(trace.setSpan(context.active(), span), async () => {
try {
this.debug(`Starting ${name}`, attributes);
const result = await operation();
span.setStatus({ code: SpanStatusCode.OK });
this.debug(`Completed ${name}`, attributes);
return result;
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error instanceof Error ? error.message : String(error),
});
span.recordException(
error instanceof Error ? error : new Error(String(error)),
);
this.error(`Failed ${name}`, error, attributes);
throw error;
} finally {
span.end();
}
});
}
/**
* Time an operation and log the duration
*/
async time<T>(
name: string,
operation: () => Promise<T>,
context?: Record<string, unknown>,
): Promise<T> {
const start = performance.now();
try {
const result = await operation();
const duration = performance.now() - start;
this.info(`${name} completed`, {
...context,
duration_ms: Math.round(duration),
});
return result;
} catch (error) {
const duration = performance.now() - start;
this.error(`${name} failed`, error, {
...context,
duration_ms: Math.round(duration),
});
throw error;
}
}
/**
* Internal logging method
*/
private log(
level: LogLevel,
message: string,
context?: Record<string, unknown>,
): void {
if (level < this.config.level) {
return;
}
const logData = {
timestamp: new Date().toISOString(),
level: LogLevel[level],
service: this.config.service,
message,
...context,
};
// Add to OpenTelemetry span if available
const activeSpan = trace.getActiveSpan();
if (activeSpan) {
activeSpan.addEvent(message, {
level: LogLevel[level],
...context,
});
}
// Console output if enabled
if (this.config.console) {
this.consoleLog(level, message, logData);
}
}
/**
* Console logging with appropriate formatting
*/
private consoleLog(
level: LogLevel,
message: string,
data: Record<string, unknown>,
): void {
const timestamp = new Date().toISOString().substring(11, 19); // HH:mm:ss
const levelStr = LogLevel[level].padEnd(5);
const prefix = `${timestamp} ${levelStr} [${this.config.service}]`;
switch (level) {
case LogLevel.DEBUG:
console.debug(`${prefix} ${message}`, data);
break;
case LogLevel.INFO:
console.info(
`${prefix} ${message}`,
Object.keys(data).length > 3 ? data : "",
);
break;
case LogLevel.WARN:
console.warn(`${prefix} ${message}`, data);
break;
case LogLevel.ERROR:
console.error(`${prefix} ${message}`, data);
break;
}
}
}
/**
* Global logger instance - configure once, use everywhere
*/
export const logger = new Logger();
/**
* Utility to suppress console output for libraries that should be quiet
*/
export function withQuietLogging<T>(operation: () => T): T {
const originalConsole = {
log: console.log,
info: console.info,
debug: console.debug,
};
// Temporarily suppress noisy console methods
console.log = () => {};
console.info = () => {};
console.debug = () => {};
try {
return operation();
} finally {
// Restore console methods
Object.assign(console, originalConsole);
}
}