@webrtc2/logger - WebRTC Logging System
Structured logging system for WebRTC applications - Debug WebRTC connections, monitor performance, and track issues across React Native, Web, and Electron platforms.
🚀 WebRTC Debugging Made Easy
@webrtc2/logger provides comprehensive logging for WebRTC development:
- 📊 Structured Logging: JSON-formatted logs with metadata
- 🔍 WebRTC-Specific: Connection states, ICE candidates, media streams
- 📱 Cross-Platform: React Native, Web browsers, Electron desktop
- ⚡ Performance Monitoring: Bitrate, latency, packet loss tracking
- 🎯 Configurable Levels: Error, warn, info, debug, trace
- 📁 Multiple Outputs: Console, file, remote logging services
📦 Installation
npm install @webrtc2/logger
🎯 Quick Start
Basic Logger Setup
import { createLogger, LogLevel } from '@webrtc2/logger';
// Create logger instance
const logger = createLogger({
name: 'WebRTC-App',
level: LogLevel.DEBUG,
enableConsole: true,
enableFile: true,
enableRemote: false
});
// Basic logging
logger.info('WebRTC connection initiated');
logger.debug('ICE candidate received', { candidate: '...' });
logger.error('Connection failed', { error: 'ICE_CONNECTION_FAILED' });
logger.warn('High packet loss detected', { packetLoss: 0.15 });
WebRTC-Specific Logging
import { WebRTCLogger } from '@webrtc2/logger';
// Specialized WebRTC logger
const webrtcLogger = new WebRTCLogger({
name: 'PeerConnection',
trackConnectionStates: true,
trackMediaStreams: true,
trackICECandidates: true,
trackStats: true
});
// Log connection events
webrtcLogger.logConnectionState('connecting', {
peerId: 'peer-123',
timestamp: Date.now()
});
webrtcLogger.logICECandidate({
candidate: 'candidate:...',
sdpMid: '0',
sdpMLineIndex: 0
});
webrtcLogger.logMediaStream('local', {
streamId: 'stream-456',
tracks: ['video', 'audio'],
constraints: { video: true, audio: true }
});
🔧 Logger Configuration
Log Levels
import { LogLevel, createLogger } from '@webrtc2/logger';
const logger = createLogger({
name: 'MyApp',
level: LogLevel.INFO, // Only INFO and above will be logged
outputs: {
console: {
enabled: true,
colorize: true,
timestamp: true
},
file: {
enabled: true,
filename: 'webrtc-debug.log',
maxSize: '10MB',
maxFiles: 5
},
remote: {
enabled: false,
endpoint: 'https://logs.example.com/api/logs',
apiKey: 'your-api-key'
}
}
});
// Log levels (from highest to lowest priority)
logger.error('Critical error occurred'); // Always logged
logger.warn('Warning message'); // Logged if level <= WARN
logger.info('Information message'); // Logged if level <= INFO
logger.debug('Debug information'); // Logged if level <= DEBUG
logger.trace('Detailed trace information'); // Logged if level <= TRACE
Component-Specific Loggers
import { createComponentLogger } from '@webrtc2/logger';
// Create loggers for different components
const peerLogger = createComponentLogger('PeerConnection');
const signalingLogger = createComponentLogger('Signaling');
const mediaLogger = createComponentLogger('MediaManager');
// Each logger has its own namespace
peerLogger.info('Peer connection established');
signalingLogger.debug('Signaling message sent', { type: 'offer' });
mediaLogger.warn('Camera permission denied');
📊 Performance Monitoring
Connection Statistics Logging
import { WebRTCStatsLogger } from '@webrtc2/logger';
const statsLogger = new WebRTCStatsLogger({
interval: 5000, // Log stats every 5 seconds
trackBitrate: true,
trackLatency: true,
trackPacketLoss: true,
trackJitter: true
});
// Start monitoring a peer connection
statsLogger.monitor(peerConnection);
// Stats are automatically logged
// [INFO] WebRTC Stats: {"bitrate": 1200, "latency": 45, "packetLoss": 0.02}
Media Quality Monitoring
import { MediaQualityLogger } from '@webrtc2/logger';
const qualityLogger = new MediaQualityLogger({
thresholds: {
excellent: { bitrate: 2000, latency: 50, packetLoss: 0.01 },
good: { bitrate: 1000, latency: 100, packetLoss: 0.05 },
poor: { bitrate: 500, latency: 200, packetLoss: 0.1 }
}
});
qualityLogger.on('quality-change', (quality, metrics) => {
logger.info(`Media quality changed to ${quality}`, metrics);
});
🌐 Cross-Platform Logging
React Native Logging
import { ReactNativeLogger } from '@webrtc2/logger';
const rnLogger = new ReactNativeLogger({
name: 'RN-WebRTC',
enableNativeLogging: true, // Use native logging APIs
enableFlipperIntegration: true, // Flipper debugging support
enableCrashReporting: true
});
// React Native specific events
rnLogger.logAppStateChange('background');
rnLogger.logPermissionRequest('camera', 'granted');
rnLogger.logNativeEvent('VideoCallStarted', { duration: 0 });
Electron Logging
import { ElectronLogger } from '@webrtc2/logger';
// Main process logger
const mainLogger = new ElectronLogger({
name: 'Electron-Main',
process: 'main',
enableIPC: true, // Enable IPC logging
logPath: '~/Library/Logs/MyApp'
});
// Renderer process logger
const rendererLogger = new ElectronLogger({
name: 'Electron-Renderer',
process: 'renderer',
enableDevTools: true // Log to DevTools console
});
mainLogger.info('Electron app started');
rendererLogger.debug('WebRTC connection in renderer');
Web Browser Logging
import { BrowserLogger } from '@webrtc2/logger';
const browserLogger = new BrowserLogger({
name: 'Web-WebRTC',
enableConsoleGroups: true, // Group related logs
enablePerformanceMarks: true, // Performance API integration
enableLocalStorage: true // Persist logs locally
});
// Browser-specific logging
browserLogger.logPageLoad();
browserLogger.logUserAgent();
browserLogger.logWebRTCSupport();
🔍 Advanced Logging Features
Contextual Logging
import { ContextualLogger } from '@webrtc2/logger';
const logger = new ContextualLogger({
name: 'WebRTC-Session',
context: {
sessionId: 'session-123',
userId: 'user-456',
roomId: 'room-789'
}
});
// Context is automatically added to all logs
logger.info('User joined room');
// Output: [INFO] User joined room {"sessionId":"session-123","userId":"user-456","roomId":"room-789"}
// Add temporary context
logger.withContext({ peerId: 'peer-abc' }).debug('Peer connection created');
Structured Data Logging
import { StructuredLogger } from '@webrtc2/logger';
const structuredLogger = new StructuredLogger({
schema: {
event: 'string',
timestamp: 'number',
data: 'object'
}
});
// Log structured events
structuredLogger.logEvent('CONNECTION_ESTABLISHED', {
peerId: 'peer-123',
connectionTime: 1500,
iceConnectionState: 'connected'
});
structuredLogger.logEvent('MEDIA_STREAM_ADDED', {
streamId: 'stream-456',
tracks: ['video', 'audio'],
resolution: { width: 1280, height: 720 }
});
Log Filtering and Searching
import { LogFilter, LogSearch } from '@webrtc2/logger';
// Filter logs by criteria
const filter = new LogFilter({
level: 'error',
component: 'PeerConnection',
timeRange: { start: Date.now() - 3600000, end: Date.now() }
});
const errorLogs = filter.apply(logs);
// Search logs
const search = new LogSearch();
const connectionLogs = search.find(logs, {
text: 'connection',
level: ['info', 'debug'],
component: 'PeerConnection'
});
📁 Log Output Formats
JSON Format
const logger = createLogger({
format: 'json',
outputs: {
file: {
enabled: true,
filename: 'webrtc.json'
}
}
});
// Output: {"level":"info","message":"Connection established","timestamp":"2023-06-26T10:30:00.000Z","component":"PeerConnection"}
Custom Format
const logger = createLogger({
format: (log) => {
return `[${log.timestamp}] ${log.level.toUpperCase()} ${log.component}: ${log.message}`;
}
});
// Output: [2023-06-26T10:30:00.000Z] INFO PeerConnection: Connection established
🚨 Error Tracking
WebRTC Error Logging
import { WebRTCErrorLogger } from '@webrtc2/logger';
const errorLogger = new WebRTCErrorLogger({
trackStackTraces: true,
trackUserAgent: true,
trackConnectionState: true,
enableCrashReporting: true
});
// Automatically log WebRTC errors
peerConnection.addEventListener('error', (error) => {
errorLogger.logWebRTCError(error, {
peerId: 'peer-123',
connectionState: peerConnection.connectionState,
iceConnectionState: peerConnection.iceConnectionState
});
});
Integration with Error Tracking Services
import { SentryLogger, BugsnagLogger } from '@webrtc2/logger';
// Sentry integration
const sentryLogger = new SentryLogger({
dsn: 'your-sentry-dsn',
environment: 'production',
tags: { component: 'webrtc' }
});
// Bugsnag integration
const bugsnagLogger = new BugsnagLogger({
apiKey: 'your-bugsnag-key',
releaseStage: 'production'
});
📚 Related Packages
- @webrtc2/client - React hooks with logging
- @webrtc2/peer - Peer connection with debug logs
- @webrtc2/utils - Utility functions with logging
- @webrtc2/types - TypeScript definitions for logs
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
📄 License
MIT License - see LICENSE for details.
Keywords: WebRTC logging, WebRTC debugging, structured logging, performance monitoring, cross-platform logging, React Native logging, Electron logging, WebRTC analytics, connection monitoring, error tracking