0
# Logger System
1
2
Configurable logging infrastructure for the Langfuse SDK with multiple severity levels, custom prefixes, timestamps, and both global singleton and instance-based usage patterns.
3
4
## Capabilities
5
6
### LogLevel Enum
7
8
Enumeration of log levels in order of severity (lowest to highest).
9
10
```typescript { .api }
11
enum LogLevel {
12
DEBUG = 0,
13
INFO = 1,
14
WARN = 2,
15
ERROR = 3
16
}
17
```
18
19
**Values:**
20
- `DEBUG = 0` - Detailed debug information for troubleshooting development issues
21
- `INFO = 1` - General informational messages about application flow
22
- `WARN = 2` - Warning messages for potentially harmful situations
23
- `ERROR = 3` - Critical errors that may cause application failure
24
25
**Import:**
26
27
```typescript
28
import { LogLevel } from '@langfuse/core';
29
```
30
31
### Logger Class
32
33
A configurable logger class that supports different log levels, custom prefixes, and optional timestamps.
34
35
```typescript { .api }
36
class Logger {
37
constructor(config?: LoggerConfig);
38
39
error(message: string, ...args: unknown[]): void;
40
warn(message: string, ...args: unknown[]): void;
41
info(message: string, ...args: unknown[]): void;
42
debug(message: string, ...args: unknown[]): void;
43
setLevel(level: LogLevel): void;
44
getLevel(): LogLevel;
45
}
46
47
interface LoggerConfig {
48
level: LogLevel;
49
prefix?: string;
50
enableTimestamp?: boolean;
51
}
52
```
53
54
**Import:**
55
56
```typescript
57
import { Logger, LoggerConfig, LogLevel } from '@langfuse/core';
58
```
59
60
#### Constructor
61
62
Creates a new Logger instance with optional configuration.
63
64
```typescript { .api }
65
constructor(config?: LoggerConfig)
66
```
67
68
**Parameters:**
69
- `config` (optional) - Configuration object for the logger
70
- `level: LogLevel` - The minimum log level to output (required if config provided)
71
- `prefix?: string` - Optional prefix to prepend to all log messages
72
- `enableTimestamp?: boolean` - Whether to include timestamps (default: true)
73
74
**Usage Example:**
75
76
```typescript
77
import { Logger, LogLevel } from '@langfuse/core';
78
79
// Create logger with debug level
80
const logger = new Logger({
81
level: LogLevel.DEBUG,
82
prefix: 'Langfuse SDK',
83
enableTimestamp: true
84
});
85
86
logger.debug('Initialization started');
87
logger.info('Connected to API');
88
logger.warn('Rate limit approaching');
89
logger.error('Failed to send batch', { batchSize: 10 });
90
```
91
92
#### error()
93
94
Logs an error message if the logger's level is ERROR or lower.
95
96
```typescript { .api }
97
/**
98
* Logs an error message with optional additional arguments
99
* @param message - The error message to log
100
* @param args - Additional arguments to log (objects, errors, etc.)
101
*/
102
error(message: string, ...args: unknown[]): void;
103
```
104
105
**Usage Example:**
106
107
```typescript
108
logger.error('Failed to fetch trace', { traceId: 'abc123' });
109
110
try {
111
// some operation
112
} catch (error) {
113
logger.error('Operation failed', error);
114
}
115
```
116
117
#### warn()
118
119
Logs a warning message if the logger's level is WARN or lower.
120
121
```typescript { .api }
122
/**
123
* Logs a warning message with optional additional arguments
124
* @param message - The warning message to log
125
* @param args - Additional arguments to log
126
*/
127
warn(message: string, ...args: unknown[]): void;
128
```
129
130
**Usage Example:**
131
132
```typescript
133
logger.warn('Retry attempt 3 of 5', { endpoint: '/api/traces' });
134
```
135
136
#### info()
137
138
Logs an informational message if the logger's level is INFO or lower.
139
140
```typescript { .api }
141
/**
142
* Logs an informational message with optional additional arguments
143
* @param message - The info message to log
144
* @param args - Additional arguments to log
145
*/
146
info(message: string, ...args: unknown[]): void;
147
```
148
149
**Usage Example:**
150
151
```typescript
152
logger.info('Batch sent successfully', { batchSize: 50 });
153
```
154
155
#### debug()
156
157
Logs a debug message if the logger's level is DEBUG.
158
159
```typescript { .api }
160
/**
161
* Logs a debug message with optional additional arguments
162
* @param message - The debug message to log
163
* @param args - Additional arguments to log
164
*/
165
debug(message: string, ...args: unknown[]): void;
166
```
167
168
**Usage Example:**
169
170
```typescript
171
logger.debug('Request details', { url: '/api/traces', method: 'POST' });
172
```
173
174
#### setLevel()
175
176
Updates the minimum log level for the logger.
177
178
```typescript { .api }
179
/**
180
* Sets the minimum log level
181
* @param level - The new minimum log level
182
*/
183
setLevel(level: LogLevel): void;
184
```
185
186
**Usage Example:**
187
188
```typescript
189
// Start with info level
190
const logger = new Logger({ level: LogLevel.INFO });
191
192
// Enable debug logging for troubleshooting
193
logger.setLevel(LogLevel.DEBUG);
194
logger.debug('Now debug messages will appear');
195
196
// Back to info for production
197
logger.setLevel(LogLevel.INFO);
198
```
199
200
#### getLevel()
201
202
Retrieves the current minimum log level.
203
204
```typescript { .api }
205
/**
206
* Gets the current minimum log level
207
* @returns The current log level
208
*/
209
getLevel(): LogLevel;
210
```
211
212
**Usage Example:**
213
214
```typescript
215
const currentLevel = logger.getLevel();
216
console.log(`Current log level: ${LogLevel[currentLevel]}`);
217
```
218
219
### Global Logger Functions
220
221
Convenience functions for working with the global singleton logger instance.
222
223
```typescript { .api }
224
function configureGlobalLogger(config: LoggerConfig): void;
225
function getGlobalLogger(): Logger;
226
function resetGlobalLogger(): void;
227
```
228
229
**Import:**
230
231
```typescript
232
import {
233
configureGlobalLogger,
234
getGlobalLogger,
235
resetGlobalLogger,
236
LogLevel
237
} from '@langfuse/core';
238
```
239
240
#### configureGlobalLogger()
241
242
Configures the global logger with new settings. Should be called early in application initialization before any logging occurs.
243
244
```typescript { .api }
245
/**
246
* Configures the global singleton logger
247
* @param config - Logger configuration
248
*/
249
function configureGlobalLogger(config: LoggerConfig): void;
250
```
251
252
**Usage Example:**
253
254
```typescript
255
import { configureGlobalLogger, LogLevel } from '@langfuse/core';
256
257
// Configure at app startup
258
configureGlobalLogger({
259
level: LogLevel.INFO,
260
prefix: 'MyApp',
261
enableTimestamp: true
262
});
263
```
264
265
#### getGlobalLogger()
266
267
Gets the global singleton logger instance.
268
269
```typescript { .api }
270
/**
271
* Gets the global singleton logger instance
272
* @returns The global logger instance
273
*/
274
function getGlobalLogger(): Logger;
275
```
276
277
**Usage Example:**
278
279
```typescript
280
import { getGlobalLogger } from '@langfuse/core';
281
282
const logger = getGlobalLogger();
283
logger.info('Using global logger');
284
```
285
286
#### resetGlobalLogger()
287
288
Resets the global logger instance and configuration. Primarily used for testing.
289
290
```typescript { .api }
291
/**
292
* Resets the global logger instance and configuration
293
* Used primarily for testing purposes
294
*/
295
function resetGlobalLogger(): void;
296
```
297
298
**Usage Example:**
299
300
```typescript
301
import { resetGlobalLogger } from '@langfuse/core';
302
303
// In test cleanup
304
afterEach(() => {
305
resetGlobalLogger();
306
});
307
```
308
309
### createLogger()
310
311
Creates a new independent Logger instance with the specified configuration. Unlike the global logger, this creates an isolated instance.
312
313
```typescript { .api }
314
/**
315
* Creates a new Logger instance independent of the global singleton
316
* @param config - Optional logger configuration
317
* @returns A new Logger instance
318
*/
319
function createLogger(config?: LoggerConfig): Logger;
320
```
321
322
**Import:**
323
324
```typescript
325
import { createLogger, LogLevel } from '@langfuse/core';
326
```
327
328
**Usage Example:**
329
330
```typescript
331
import { createLogger, LogLevel } from '@langfuse/core';
332
333
// Create custom logger for a specific module
334
const moduleLogger = createLogger({
335
level: LogLevel.DEBUG,
336
prefix: 'TraceProcessor',
337
enableTimestamp: true
338
});
339
340
moduleLogger.debug('Processing trace batch');
341
```
342
343
### logger (LoggerSingleton)
344
345
Direct access to the LoggerSingleton class for advanced usage patterns. This provides an alternative way to access the global logger singleton.
346
347
```typescript { .api }
348
/**
349
* The singleton logger instance for convenient access
350
*/
351
export const logger: typeof LoggerSingleton;
352
353
class LoggerSingleton {
354
static getInstance(): Logger;
355
static configure(config: LoggerConfig): void;
356
static reset(): void;
357
}
358
```
359
360
**Import:**
361
362
```typescript
363
import { logger } from '@langfuse/core';
364
```
365
366
**Usage Example:**
367
368
```typescript
369
import { logger, LogLevel } from '@langfuse/core';
370
371
// Access global logger via singleton
372
const globalLogger = logger.getInstance();
373
globalLogger.info('Quick logging access');
374
375
// Configure via singleton
376
logger.configure({
377
level: LogLevel.DEBUG,
378
prefix: 'Langfuse SDK',
379
enableTimestamp: true
380
});
381
382
// Reset via singleton (useful for testing)
383
logger.reset();
384
```
385
386
## Usage Patterns
387
388
### Global Logger Pattern
389
390
Use the global logger singleton for application-wide logging with consistent configuration.
391
392
```typescript
393
import { configureGlobalLogger, getGlobalLogger, LogLevel } from '@langfuse/core';
394
395
// Configure once at application startup
396
configureGlobalLogger({
397
level: process.env.NODE_ENV === 'production' ? LogLevel.INFO : LogLevel.DEBUG,
398
prefix: 'Langfuse',
399
enableTimestamp: true
400
});
401
402
// Use anywhere in your application
403
function processTraces() {
404
const logger = getGlobalLogger();
405
logger.info('Starting trace processing');
406
// ... processing logic
407
}
408
```
409
410
### Instance-Based Pattern
411
412
Create dedicated logger instances for different modules or components.
413
414
```typescript
415
import { createLogger, LogLevel } from '@langfuse/core';
416
417
class TraceService {
418
private logger: Logger;
419
420
constructor() {
421
this.logger = createLogger({
422
level: LogLevel.INFO,
423
prefix: 'TraceService'
424
});
425
}
426
427
async processTrace(traceId: string) {
428
this.logger.debug('Processing trace', { traceId });
429
try {
430
// ... processing
431
this.logger.info('Trace processed successfully', { traceId });
432
} catch (error) {
433
this.logger.error('Failed to process trace', { traceId, error });
434
throw error;
435
}
436
}
437
}
438
```
439
440
### Environment-Based Configuration
441
442
Configure logging based on environment variables.
443
444
```typescript
445
import { configureGlobalLogger, LogLevel, getEnv } from '@langfuse/core';
446
447
// Map environment variable to LogLevel
448
const logLevelMap: Record<string, LogLevel> = {
449
'DEBUG': LogLevel.DEBUG,
450
'INFO': LogLevel.INFO,
451
'WARN': LogLevel.WARN,
452
'ERROR': LogLevel.ERROR
453
};
454
455
const logLevelStr = getEnv('LANGFUSE_LOG_LEVEL') || 'INFO';
456
const logLevel = logLevelMap[logLevelStr] ?? LogLevel.INFO;
457
458
configureGlobalLogger({
459
level: logLevel,
460
prefix: 'Langfuse SDK',
461
enableTimestamp: true
462
});
463
```
464
465
### Conditional Debug Logging
466
467
Enable debug logging only when needed without affecting production.
468
469
```typescript
470
import { Logger, LogLevel } from '@langfuse/core';
471
472
const logger = new Logger({
473
level: process.env.DEBUG ? LogLevel.DEBUG : LogLevel.INFO
474
});
475
476
// Debug messages only appear when DEBUG env var is set
477
logger.debug('Detailed request information', {
478
headers: { /* ... */ },
479
body: { /* ... */ }
480
});
481
```
482
483
## Type Definitions
484
485
```typescript { .api }
486
enum LogLevel {
487
DEBUG = 0,
488
INFO = 1,
489
WARN = 2,
490
ERROR = 3
491
}
492
493
interface LoggerConfig {
494
level: LogLevel;
495
prefix?: string;
496
enableTimestamp?: boolean;
497
}
498
499
class Logger {
500
constructor(config?: LoggerConfig);
501
error(message: string, ...args: unknown[]): void;
502
warn(message: string, ...args: unknown[]): void;
503
info(message: string, ...args: unknown[]): void;
504
debug(message: string, ...args: unknown[]): void;
505
setLevel(level: LogLevel): void;
506
getLevel(): LogLevel;
507
}
508
```
509
510
## Best Practices
511
512
1. **Configure Early**: Set up the global logger at application startup before any SDK operations
513
2. **Use Appropriate Levels**: Reserve ERROR for actual failures, WARN for potential issues, INFO for key events
514
3. **Include Context**: Pass relevant context objects as additional arguments for better debugging
515
4. **Avoid Sensitive Data**: Never log API keys, passwords, or other sensitive information
516
5. **Production Logging**: Use INFO or WARN level in production to reduce noise
517
6. **Development Debugging**: Enable DEBUG level during development for detailed troubleshooting
518
7. **Module Prefixes**: Use unique prefixes for different modules when creating multiple logger instances
519
8. **Error Objects**: Always pass Error objects to logging methods for proper stack traces
520