0
# Telemetry and Monitoring
1
2
Comprehensive telemetry system with OpenTelemetry integration for monitoring AI interactions, system performance, and user behavior analytics.
3
4
## Capabilities
5
6
### Telemetry Initialization
7
8
Core telemetry setup and configuration with support for multiple backends.
9
10
```typescript { .api }
11
/**
12
* Telemetry target destinations
13
*/
14
enum TelemetryTarget {
15
/** Google Cloud Platform */
16
GCP = 'gcp',
17
/** Local telemetry collection */
18
LOCAL = 'local'
19
}
20
21
/**
22
* Initialize telemetry system
23
* @param target - Telemetry target destination
24
* @param options - Additional initialization options
25
*/
26
function initializeTelemetry(
27
target: TelemetryTarget,
28
options?: {
29
endpoint?: string;
30
apiKey?: string;
31
sampleRate?: number;
32
enableTracing?: boolean;
33
enableMetrics?: boolean;
34
enableLogging?: boolean;
35
}
36
): void;
37
38
/**
39
* Shutdown telemetry system and flush pending data
40
*/
41
function shutdownTelemetry(): Promise<void>;
42
43
/**
44
* Check if telemetry SDK is initialized
45
* @returns True if telemetry is initialized
46
*/
47
function isTelemetrySdkInitialized(): boolean;
48
49
/**
50
* Default telemetry target
51
*/
52
const DEFAULT_TELEMETRY_TARGET: TelemetryTarget;
53
54
/**
55
* Default OTLP endpoint for telemetry
56
*/
57
const DEFAULT_OTLP_ENDPOINT: string;
58
```
59
60
### Event Logging Functions
61
62
High-level logging functions for common events and interactions.
63
64
```typescript { .api }
65
/**
66
* Log CLI configuration settings
67
* @param config - Configuration object
68
* @param metadata - Additional metadata
69
*/
70
function logCliConfiguration(
71
config: any,
72
metadata?: Record<string, any>
73
): void;
74
75
/**
76
* Log user prompt interaction
77
* @param prompt - User prompt text
78
* @param metadata - Additional metadata
79
*/
80
function logUserPrompt(
81
prompt: string,
82
metadata?: {
83
length?: number;
84
language?: string;
85
sessionId?: string;
86
}
87
): void;
88
89
/**
90
* Log tool call execution
91
* @param toolName - Name of the tool
92
* @param params - Tool parameters
93
* @param result - Tool execution result
94
* @param metadata - Additional metadata
95
*/
96
function logToolCall(
97
toolName: string,
98
params: any,
99
result?: any,
100
metadata?: {
101
duration?: number;
102
success?: boolean;
103
error?: string;
104
}
105
): void;
106
107
/**
108
* Log API request to AI services
109
* @param model - Model name
110
* @param request - Request details
111
* @param metadata - Additional metadata
112
*/
113
function logApiRequest(
114
model: string,
115
request: any,
116
metadata?: {
117
tokens?: number;
118
endpoint?: string;
119
requestId?: string;
120
}
121
): void;
122
123
/**
124
* Log API error responses
125
* @param error - Error details
126
* @param context - Error context
127
*/
128
function logApiError(
129
error: any,
130
context?: {
131
model?: string;
132
endpoint?: string;
133
requestId?: string;
134
}
135
): void;
136
137
/**
138
* Log API response details
139
* @param response - Response details
140
* @param metadata - Additional metadata
141
*/
142
function logApiResponse(
143
response: any,
144
metadata?: {
145
tokens?: number;
146
duration?: number;
147
model?: string;
148
}
149
): void;
150
151
/**
152
* Log flash fallback usage
153
* @param originalModel - Original model that failed
154
* @param fallbackModel - Fallback model used
155
* @param reason - Reason for fallback
156
*/
157
function logFlashFallback(
158
originalModel: string,
159
fallbackModel: string,
160
reason: string
161
): void;
162
163
/**
164
* Log slash command usage
165
* @param command - Slash command name
166
* @param args - Command arguments
167
* @param metadata - Additional metadata
168
*/
169
function logSlashCommand(
170
command: string,
171
args: any[],
172
metadata?: {
173
success?: boolean;
174
duration?: number;
175
}
176
): void;
177
178
/**
179
* Log conversation finished event
180
* @param sessionId - Session identifier
181
* @param metadata - Conversation metadata
182
*/
183
function logConversationFinishedEvent(
184
sessionId: string,
185
metadata?: {
186
duration?: number;
187
messageCount?: number;
188
toolCallCount?: number;
189
}
190
): void;
191
192
/**
193
* Log kitty sequence overflow events
194
* @param sequenceLength - Length of the sequence
195
* @param metadata - Additional metadata
196
*/
197
function logKittySequenceOverflow(
198
sequenceLength: number,
199
metadata?: Record<string, any>
200
): void;
201
202
/**
203
* Log chat compression events
204
* @param originalTokens - Original token count
205
* @param compressedTokens - Compressed token count
206
* @param compressionRatio - Compression ratio
207
*/
208
function logChatCompression(
209
originalTokens: number,
210
compressedTokens: number,
211
compressionRatio: number
212
): void;
213
```
214
215
### Event Classes
216
217
Structured event classes for detailed telemetry data collection.
218
219
```typescript { .api }
220
/**
221
* Base event class for telemetry
222
*/
223
abstract class TelemetryEvent {
224
constructor(
225
public readonly eventType: string,
226
public readonly timestamp: Date = new Date()
227
);
228
229
abstract toJson(): Record<string, any>;
230
}
231
232
/**
233
* End session event
234
*/
235
class EndSessionEvent extends TelemetryEvent {
236
constructor(
237
public readonly sessionId: string,
238
public readonly duration: number,
239
public readonly metadata?: Record<string, any>
240
);
241
242
toJson(): Record<string, any>;
243
}
244
245
/**
246
* User prompt event
247
*/
248
class UserPromptEvent extends TelemetryEvent {
249
constructor(
250
public readonly prompt: string,
251
public readonly length: number,
252
public readonly sessionId?: string
253
);
254
255
toJson(): Record<string, any>;
256
}
257
258
/**
259
* API request event
260
*/
261
class ApiRequestEvent extends TelemetryEvent {
262
constructor(
263
public readonly model: string,
264
public readonly endpoint: string,
265
public readonly requestSize: number,
266
public readonly requestId?: string
267
);
268
269
toJson(): Record<string, any>;
270
}
271
272
/**
273
* API error event
274
*/
275
class ApiErrorEvent extends TelemetryEvent {
276
constructor(
277
public readonly error: string,
278
public readonly statusCode: number,
279
public readonly model?: string,
280
public readonly requestId?: string
281
);
282
283
toJson(): Record<string, any>;
284
}
285
286
/**
287
* API response event
288
*/
289
class ApiResponseEvent extends TelemetryEvent {
290
constructor(
291
public readonly model: string,
292
public readonly responseSize: number,
293
public readonly duration: number,
294
public readonly tokens?: number
295
);
296
297
toJson(): Record<string, any>;
298
}
299
300
/**
301
* Flash fallback event
302
*/
303
class FlashFallbackEvent extends TelemetryEvent {
304
constructor(
305
public readonly originalModel: string,
306
public readonly fallbackModel: string,
307
public readonly reason: string
308
);
309
310
toJson(): Record<string, any>;
311
}
312
313
/**
314
* Start session event
315
*/
316
class StartSessionEvent extends TelemetryEvent {
317
constructor(
318
public readonly sessionId: string,
319
public readonly metadata?: Record<string, any>
320
);
321
322
toJson(): Record<string, any>;
323
}
324
325
/**
326
* Tool call event
327
*/
328
class ToolCallEvent extends TelemetryEvent {
329
constructor(
330
public readonly toolName: string,
331
public readonly parameters: any,
332
public readonly result?: any,
333
public readonly duration?: number,
334
public readonly success?: boolean
335
);
336
337
toJson(): Record<string, any>;
338
}
339
340
/**
341
* Conversation finished event
342
*/
343
class ConversationFinishedEvent extends TelemetryEvent {
344
constructor(
345
public readonly sessionId: string,
346
public readonly messageCount: number,
347
public readonly duration: number,
348
public readonly toolCallCount?: number
349
);
350
351
toJson(): Record<string, any>;
352
}
353
354
/**
355
* Kitty sequence overflow event
356
*/
357
class KittySequenceOverflowEvent extends TelemetryEvent {
358
constructor(
359
public readonly sequenceLength: number,
360
public readonly metadata?: Record<string, any>
361
);
362
363
toJson(): Record<string, any>;
364
}
365
```
366
367
### Utility Classes
368
369
Utility classes for telemetry management and rate limiting.
370
371
```typescript { .api }
372
/**
373
* High water mark tracker for monitoring peak values
374
*/
375
class HighWaterMarkTracker {
376
constructor(
377
private readonly metricName: string,
378
private readonly reportingInterval: number = 60000
379
);
380
381
/**
382
* Record a new value
383
* @param value - Value to record
384
*/
385
record(value: number): void;
386
387
/**
388
* Get current high water mark
389
* @returns Current peak value
390
*/
391
getHighWaterMark(): number;
392
393
/**
394
* Reset high water mark
395
*/
396
reset(): void;
397
398
/**
399
* Start automatic reporting
400
*/
401
startReporting(): void;
402
403
/**
404
* Stop automatic reporting
405
*/
406
stopReporting(): void;
407
}
408
409
/**
410
* Rate limiter for telemetry events
411
*/
412
class RateLimiter {
413
constructor(
414
private readonly maxEvents: number,
415
private readonly windowMs: number
416
);
417
418
/**
419
* Check if event should be allowed
420
* @param eventKey - Event identifier
421
* @returns True if event should be allowed
422
*/
423
shouldAllow(eventKey: string): boolean;
424
425
/**
426
* Get current rate limit status
427
* @param eventKey - Event identifier
428
* @returns Rate limit status
429
*/
430
getStatus(eventKey: string): {
431
remainingEvents: number;
432
resetTime: Date;
433
};
434
435
/**
436
* Reset rate limit for event
437
* @param eventKey - Event identifier
438
*/
439
reset(eventKey: string): void;
440
}
441
```
442
443
### Session Management
444
445
Session identifier management for tracking user sessions.
446
447
```typescript { .api }
448
/**
449
* Get current session identifier
450
* @returns Session ID string
451
*/
452
const sessionId: string;
453
454
/**
455
* Generate new session identifier
456
* @returns New session ID
457
*/
458
function generateSessionId(): string;
459
460
/**
461
* Set current session identifier
462
* @param id - Session ID to set
463
*/
464
function setSessionId(id: string): void;
465
```
466
467
### Browser Utilities
468
469
Browser-related utilities for web-based telemetry.
470
471
```typescript { .api }
472
/**
473
* Browser detection and utilities
474
*/
475
namespace BrowserUtils {
476
/**
477
* Check if running in browser environment
478
* @returns True if in browser
479
*/
480
function isBrowser(): boolean;
481
482
/**
483
* Get browser information
484
* @returns Browser details
485
*/
486
function getBrowserInfo(): {
487
name: string;
488
version: string;
489
platform: string;
490
userAgent: string;
491
};
492
493
/**
494
* Get page performance metrics
495
* @returns Performance metrics
496
*/
497
function getPerformanceMetrics(): {
498
loadTime: number;
499
domContentLoaded: number;
500
firstPaint: number;
501
firstContentfulPaint: number;
502
};
503
504
/**
505
* Track page view
506
* @param page - Page identifier
507
* @param metadata - Additional metadata
508
*/
509
function trackPageView(
510
page: string,
511
metadata?: Record<string, any>
512
): void;
513
}
514
```
515
516
### OpenTelemetry Integration
517
518
Direct access to OpenTelemetry APIs and semantic conventions.
519
520
```typescript { .api }
521
// Re-exported OpenTelemetry APIs
522
export * from '@opentelemetry/api';
523
export * from '@opentelemetry/semantic-conventions';
524
525
/**
526
* Get OpenTelemetry tracer instance
527
* @param name - Tracer name
528
* @returns Tracer instance
529
*/
530
function getTracer(name: string): any; // Tracer type from @opentelemetry/api
531
532
/**
533
* Get OpenTelemetry meter instance
534
* @param name - Meter name
535
* @returns Meter instance
536
*/
537
function getMeter(name: string): any; // Meter type from @opentelemetry/api
538
539
/**
540
* Create custom span
541
* @param name - Span name
542
* @param operation - Operation to trace
543
* @returns Operation result
544
*/
545
function withSpan<T>(
546
name: string,
547
operation: (span: any) => T
548
): T;
549
```
550
551
**Usage Examples:**
552
553
```typescript
554
import {
555
initializeTelemetry,
556
TelemetryTarget,
557
logUserPrompt,
558
logToolCall,
559
logApiRequest,
560
UserPromptEvent,
561
HighWaterMarkTracker,
562
sessionId
563
} from '@google/gemini-cli-core';
564
565
// Initialize telemetry
566
initializeTelemetry(TelemetryTarget.GCP, {
567
endpoint: 'https://telemetry.example.com',
568
sampleRate: 0.1,
569
enableTracing: true,
570
enableMetrics: true
571
});
572
573
// Log user interactions
574
logUserPrompt('What files are in my project?', {
575
length: 28,
576
sessionId: sessionId,
577
language: 'english'
578
});
579
580
// Log tool executions
581
const startTime = Date.now();
582
// ... tool execution ...
583
const endTime = Date.now();
584
585
logToolCall('ls', { path: '.' }, ['file1.ts', 'file2.ts'], {
586
duration: endTime - startTime,
587
success: true
588
});
589
590
// Log API interactions
591
logApiRequest('gemini-1.5-flash', {
592
contents: [{ role: 'user', parts: [{ text: 'Hello' }] }]
593
}, {
594
tokens: 150,
595
requestId: 'req-123'
596
});
597
598
// Create structured events
599
const promptEvent = new UserPromptEvent(
600
'Analyze this codebase',
601
20,
602
sessionId
603
);
604
605
console.log('Event data:', promptEvent.toJson());
606
607
// High water mark tracking
608
const memoryTracker = new HighWaterMarkTracker('memory_usage', 30000);
609
memoryTracker.startReporting();
610
611
// Record memory usage periodically
612
setInterval(() => {
613
const memoryUsage = process.memoryUsage().heapUsed;
614
memoryTracker.record(memoryUsage);
615
}, 5000);
616
617
// Custom span tracing
618
import { withSpan } from '@google/gemini-cli-core';
619
620
const result = withSpan('file-processing', (span) => {
621
span.setAttributes({
622
'file.path': '/path/to/file.ts',
623
'file.size': 1024
624
});
625
626
// Process file...
627
return processFile('/path/to/file.ts');
628
});
629
630
// Shutdown telemetry on exit
631
process.on('beforeExit', async () => {
632
await shutdownTelemetry();
633
});
634
```