@ringcentral/mfe-logger

A micro frontends framework for building Web applications
Overview
@ringcentral/mfe-logger is a flexible logging system based on Roarr, providing structured logging with configurable transports, middlewares, and integrations. It's designed to be extensible and adaptable to different environments and use cases.
Features
- Multiple log levels (log, trace, debug, info, warn, error, fatal)
- Configurable transports for different output destinations
- Middleware support for log manipulation and transformation
- Integration capabilities with other systems
- Tag-based logging for better organization
- Storage persistence for log retrieval and analysis
- Error tracking integration
Usage
Installation
npm install @ringcentral/mfe-logger
yarn add @ringcentral/mfe-logger
You can visit https://github.com/ringcentral/ringcentral-mfe for more documentation.
Basic Usage
import { useLogger, ConsoleTransport, ScriptErrorIntegration } from '@ringcentral/mfe-logger';
const logger = useLogger({
name: 'my-application',
version: '1.0.0',
environment: 'development',
enabled: true,
transports: [
new ConsoleTransport({
enabled: true
})
],
integrations: [
new ScriptErrorIntegration({
enabled: true
})
]
});
logger.info('Application started');
logger.debug('Debug information', { key: 'value' });
logger.warn('Warning message');
logger.error('Error occurred', new Error('Something went wrong'));
const componentLogger = logger.tag('Component');
componentLogger.info('Component initialized');
Available Transports
ConsoleTransport
Outputs logs to the browser console.
import { ConsoleTransport } from '@ringcentral/mfe-logger';
const consoleTransport = new ConsoleTransport({
enabled: true,
filter: 'context.logLevel:>= 20',
ignoreRule: [/sensitive/],
storage: localStorage
});
consoleTransport.enable();
consoleTransport.disable();
consoleTransport.setFilter('context.logLevel:>= 30');
StorageTransport
Persists logs to browser storage using IndexedDB.
import { StorageTransport } from '@ringcentral/mfe-logger';
const storageTransport = new StorageTransport({
enabled: true,
prefix: 'myapp',
batchNumber: 1024 * 256,
batchTimeout: 1000 * 60 * 2,
expired: 1000 * 60 * 60 * 48,
maxLogsSize: 1024 * 1024 * 50,
recentTime: 1000 * 60 * 30
});
await storageTransport.saveDB();
const logs = await storageTransport.getLogs();
const customLogs = await storageTransport.getLogs({
name: 'custom-export',
recentTime: 1000 * 60 * 60 * 24,
extraLogs: [
{
fileName: 'extra.log',
log: 'Additional log content'
}
]
});
await storageTransport.downloadLogs();
Storage Transport Default Configuration
The storage transport implements the following default behavior:
- Batch Size: 512KB - Logs are saved to storage when the batch size exceeds 512KB
- Batch Timeout: 5 minutes - Even if the batch size is not reached, logs are saved every 5 minutes
- Maximum Logs Size: 100MB - When the total size of logs exceeds 100MB, older logs are pruned
- Expiration Time: 1 day - Logs older than 1 day are automatically deleted
- Recent Time: 1 hour - The
getLogs and downloadLogs methods retrieve logs from the last hour by default
These defaults can be customized when initializing the storage transport.
Available Integrations
ScriptErrorIntegration
Automatically captures unhandled errors and promise rejections.
import { ScriptErrorIntegration } from '@ringcentral/mfe-logger';
const scriptErrorIntegration = new ScriptErrorIntegration({
enabled: true
});
Console Integration
Provides integration with the browser console for easier debugging.
import { ConsoleIntegration } from '@ringcentral/mfe-logger';
const consoleIntegration = new ConsoleIntegration();
HTTP Client Integration
Intended for integrating with HTTP clients to log network requests.
import { HttpClientIntegration } from '@ringcentral/mfe-logger';
const httpClientIntegration = new HttpClientIntegration();
Advanced Usage
Creating a Tagged Logger
Tagged loggers are useful for organizing logs by component or feature:
const featureLogger = logger.tag('FeatureName');
const subFeatureLogger = logger.tag('FeatureName', 'SubFeature');
subFeatureLogger.info('Log message');
Enabling/Disabling Logging
You can enable or disable logging at runtime:
logger.disable();
logger.enable();
if (logger.enabled) {
}
Custom Middleware
Middlewares can transform log context and parameters:
import { useLogger } from '@ringcentral/mfe-logger';
const myMiddleware = {
handleContext(context) {
return {
...context,
customProperty: 'value'
};
},
handleParams(params) {
if (Array.isArray(params)) {
return params.map(p => typeof p === 'object' ? JSON.stringify(p) : p).join(' ');
}
return params;
}
};
const logger = useLogger({
name: 'my-app',
middlewares: [myMiddleware]
});
Best Practices
-
Appropriate Log Levels: Use the correct log level based on the importance and type of information:
trace: Extremely detailed information (rarely used)
debug: Debugging information useful during development
info: General information about application flow
warn: Warning situations that don't cause errors
error: Error conditions that affect operation
fatal: Critical errors causing application shutdown
-
Structured Logging: Pass objects along with messages for better searchability:
logger.info('User logged in', { userId: '123', timestamp: Date.now() });
-
Tagged Loggers: Create tagged loggers for different parts of your application to easily filter logs.
-
Error Handling: Use the error transport for catching unhandled errors in production.
-
Performance Considerations: Be mindful of the performance impact of verbose logging in production environments.