API Reference
Complete API documentation for the Logger utility.
Logger Class
Constructor
new Logger(config?: LoggerConfig)Creates a new Logger instance with optional configuration.
Parameters:
config(optional): Configuration object to customize logger behavior
Example:
const logger = new Logger({
debugMode: true,
serverUrl: 'https://api.example.com/logs',
})Methods
init()
async init(): Promise<void>Initializes the logger and sets up storage. Must be called before using logging methods.
Returns: Promise that resolves when initialization is complete
Example:
const logger = new Logger()
await logger.init()info()
async info(title: string, data: Record<string, any> = {}): Promise<void>Logs an informational message.
Parameters:
title: Descriptive title for the log entrydata: Additional context data (optional)
Example:
await logger.info('User login', { userId: 123, timestamp: Date.now() })warn()
async warn(title: string, data: Record<string, any> = {}): Promise<void>Logs a warning message.
Parameters:
title: Descriptive title for the log entrydata: Additional context data (optional)
Example:
await logger.warn('High memory usage', { usage: '85%', threshold: '80%' })error()
async error(title: string, data: Record<string, any> = {}): Promise<void>Logs an error message.
Parameters:
title: Descriptive title for the log entrydata: Additional context data (optional)
Example:
await logger.error('Database connection failed', {
error: 'Connection timeout',
database: 'users_db',
})debug()
async debug(title: string, data: Record<string, any> = {}): Promise<void>Logs a debug message. Only printed to console when debugMode is enabled.
Parameters:
title: Descriptive title for the log entrydata: Additional context data (optional)
Example:
await logger.debug('Processing user data', { userId: 123, step: 'validation' })trace()
async trace(title: string, data: Record<string, any> = {}): Promise<void>Logs a trace message. Only printed to console when debugMode is enabled.
Parameters:
title: Descriptive title for the log entrydata: Additional context data (optional)
Example:
await logger.trace('Function entry', { function: 'processPayment', args: [orderId] })forceUpload()
async forceUpload(): Promise<void>Forces immediate upload of all pending logs, regardless of upload strategy.
Example:
await logger.forceUpload()getAllLogs()
async getAllLogs(): Promise<LogEntry[]>Retrieves all logs stored locally.
Returns: Array of log entries
Example:
const logs = await logger.getAllLogs()
console.log(`Total logs: ${logs.length}`)clearAllLogs()
async clearAllLogs(): Promise<void>Removes all logs from local storage.
Example:
await logger.clearAllLogs()getConfig()
async getConfig(): Promise<Required<LoggerConfig>>Returns the current logger configuration.
Returns: Current configuration object
Example:
const config = await logger.getConfig()
console.log('Debug mode:', config.debugMode)updateConfig()
async updateConfig(newConfig: Partial<LoggerConfig>): Promise<void>Updates the logger configuration at runtime.
Parameters:
newConfig: Partial configuration object with properties to update
Example:
await logger.updateConfig({
debugMode: false,
uploadStrategy: 'immediate',
})destroy()
destroy(): voidCleans up resources and stops all background processes. Call when done with the logger.
Example:
logger.destroy()Type Definitions
LoggerConfig
interface LoggerConfig {
serverUrl?: string // Server URL for log upload
debugMode?: boolean // Enable debug console output (default: true)
uploadLogs?: boolean // Enable server upload (default: true)
logExpiration?: number // Log expiration in days (default: 3)
uploadStrategy?: UploadStrategy // Upload timing (default: 'idle')
batchSize?: number // Batch size for uploads (default: 50)
}LogEntry
interface LogEntry {
id: string // Unique identifier
level: LogLevel // Log level
title: string // Log title
data: Record<string, any> // Additional data
timestamp: number // Creation timestamp
uploaded?: boolean // Upload status
}LogLevel
type LogLevel = 'info' | 'warn' | 'error' | 'debug' | 'trace'UploadStrategy
type UploadStrategy = 'idle' | 'immediate'Default Configuration
const DEFAULT_CONFIG: Required<LoggerConfig> = {
serverUrl: '',
debugMode: true,
uploadLogs: true,
logExpiration: 3,
uploadStrategy: 'idle',
batchSize: 50,
}Error Handling
All logger methods handle errors gracefully and will not throw exceptions under normal circumstances. Errors are logged to the console for debugging purposes.
Common Error Scenarios
- Storage Initialization Failure: Logger continues to work with console-only output
- Upload Failures: Logs remain in local storage for retry
- Invalid Configuration: Default values are used with console warnings
Error Examples
// Logger handles storage errors gracefully
const logger = new Logger()
try {
await logger.init()
} catch (error) {
console.error('Logger initialization failed:', error)
// Logger still works, just without storage
}
// Upload errors don't affect logging
await logger.info('This will be logged even if upload fails')Browser Compatibility
- Modern Browsers: Chrome 60+, Firefox 55+, Safari 12+, Edge 79+
- Required APIs: IndexedDB, ES2020 features, fetch API
- Optional Features: Performance API (for timing), Memory API (for monitoring)
Performance Considerations
- Memory Usage: Logs are stored efficiently in IndexedDB
- CPU Impact: Minimal overhead for log creation and storage
- Network Usage: Configurable batch sizes minimize network requests
- Storage Cleanup: Automatic cleanup prevents storage overflow
Thread Safety
The logger is designed for single-threaded browser environments. All operations are async and properly queued to prevent race conditions.
Migration Guide
From Console Logging
// Before
console.log('User action', { userId: 123 })
console.error('Something failed', error)
// After
await logger.info('User action', { userId: 123 })
await logger.error('Something failed', { error: error.message })From Other Logging Libraries
// Winston-style
logger.info('message', { meta: 'data' })
// Logger utility style
await logger.info('message', { meta: 'data' })Best Practices
- Always Initialize: Call
init()before logging - Use Appropriate Levels: Choose the right log level for each message
- Include Context: Add relevant data to log entries
- Handle Cleanup: Call
destroy()when done - Configure for Environment: Use different configs for dev/prod
Examples
See the Examples section for comprehensive usage examples and integration patterns.