cross-log
Version:
A universal logging package that works in both browser and Node.js environments with environment variable configuration
229 lines (169 loc) โข 7.13 kB
Markdown
A universal logging package that works seamlessly in both browser and Node.js environments with environment variable configuration and zero dependencies.
[](https://badge.fury.io/js/cross-log)
[](https://github.com/dev-ignis/cross-log/actions)
[](https://coveralls.io/github/dev-ignis/cross-log?branch=main)
[](https://www.typescriptlang.org)
- **๐ Universal**: Single package works in browser and Node.js
- **โ๏ธ Environment-driven**: Configuration via environment variables with smart defaults
- **๐ชถ Zero dependencies**: Lightweight and secure
- **๐ TypeScript-first**: Full type safety and IntelliSense
- **๐ Backward compatible**: Drop-in replacement for console logging
- **๐จ Styled output**: Colors in browser console and ANSI colors in terminal
- **๐พ Persistent storage**: Browser localStorage integration for settings
- **๐ท๏ธ Category-based**: Organize logs by categories with individual control
- **โก Performance-optimized**: Duplicate log prevention and minimal overhead when disabled
```bash
npm install cross-log
```
```typescript
import logger from 'cross-log';
// Works immediately with smart defaults
logger.info('Application started'); // โ
Always shown
logger.debug('Debug information'); // โ
Shown in development
logger.warn('Warning message'); // โ ๏ธ Always shown
logger.error('Error occurred'); // โ Always shown
```
```typescript
import { createLogger, LogLevel } from 'cross-log';
const logger = createLogger({
minLevel: LogLevel.WARN,
showTimestamp: true,
colors: { enabled: false }
});
logger.warn('This will show');
logger.debug('This will not show');
```
Configure via environment variables (all optional with smart defaults):
```bash
# Core settings
LOG_LEVEL=DEBUG
LOGGER_ENABLED=true
LOGGER_TIMESTAMPS=true
LOGGER_STACK_TRACES=true
LOGGER_COLORS=true
LOGGER_STORAGE_ENABLED=true
LOGGER_STORAGE_KEY_PREFIX=myapp
LOGGER_BROWSER_CONTROLS=true
LOGGER_WINDOW_NAMESPACE=__Cross-Logger
LOGGER_COLOR_DEBUG=
LOGGER_COLOR_INFO=
LOGGER_COLOR_WARN=
LOGGER_COLOR_ERROR=
LOGGER_ANSI_DEBUG=36
LOGGER_ANSI_INFO=36
LOGGER_ANSI_WARN=33
LOGGER_ANSI_ERROR=31
```
```typescript
import { createLogger, LogLevel } from 'cross-log';
const logger = createLogger({
minLevel: LogLevel.INFO,
showTimestamp: false,
colors: {
enabled: true,
browser: {
info: '#custom-color'
}
}
});
```
```typescript
// Enable specific categories
logger.enableCategory('api', LogLevel.DEBUG);
logger.enableCategory('ui', LogLevel.INFO);
// Disable noisy categories
logger.disableCategory('metrics');
// Use categories
logger.debug('Database query executed', 'db');
logger.info('Component rendered', 'ui');
```
In development, use these browser console functions:
```javascript
// Enable all logging
window.enableUniversalLoggerLogging();
// Disable all logging
window.disableUniversalLoggerLogging();
// Check status
window.universalLoggerLoggingStatus();
// Access logger directly
window.__universalLogger.setLevel(0);
```
| Environment | LOG_LEVEL | COLORS | BROWSER_CONTROLS | STORAGE |
|-------------|-----------|--------|------------------|---------|
| **Development Browser** | DEBUG | โ
| โ
| โ
|
| **Production Browser** | WARN | โ
| โ | โ
|
| **Development Node.js** | DEBUG | โ
| โ | โ |
| **Production Node.js** | WARN | โ | โ | โ |
Universal Logger is designed to be lightweight and efficient. Here are the performance benchmarks:
```text
====================================
Benchmark Results
====================================
Disabled Logger: ~20,000,000 ops/sec
Production Logger: ~4,500,000 ops/sec
Development Logger: ~4,800,000 ops/sec
Filtered Category: ~4,400,000 ops/sec
Error Logging: ~5,000,000 ops/sec
Native Console.log: ~84,000,000 ops/sec
```
- **Disabled Logger**: Only 76% overhead vs native console (~20M ops/sec)
- **Development Logger**: 94% overhead with full features but still performs at ~4.8M ops/sec
- **Production Configurations**: All active logging configurations handle 4-5 million operations per second
- **Practical Impact**: Even at peak load, the performance impact is negligible for most applications
> Run your own benchmarks with `node tests/benchmarks/logger-benchmark.js` after building the package
## ๐งช Test Coverage
Universal Logger is thoroughly tested with both unit and integration tests for all environments.
```text
-------------------|----------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------------|----------|----------|---------|---------|-------------------
All files | 80.6 | 92.25 | 68.36 | 80.04 |
```
- **Unit Tests**: Cover individual components, utilities, and logger implementations
- **Integration Tests**: Ensure proper operation in both Node.js and browser environments
- **Cross-Environment Tests**: Verify consistent behavior across platforms
The test suite includes:
- API functionality testing
- Environment detection and adaptation
- Configuration inheritance and override validation
- Category filtering effectiveness
- Log level control validation
Run the tests with coverage report using:
```bash
npm run test -- --coverage
```
## API Reference
### Logger Methods
- `debug(message, category?, ...args)` - Debug level logging
- `info(message, category?, ...args)` - Info level logging
- `warn(message, category?, ...args)` - Warning level logging
- `error(message, category?, ...args)` - Error level logging
### Configuration Methods
- `setLevel(level)` - Set minimum log level
- `configure(config)` - Update configuration
- `enableCategory(name, level?)` - Enable category logging
- `disableCategory(name)` - Disable category logging
- `enableAll()` - Enable all logging
- `disableAll()` - Disable all logging
- `getConfig()` - Get current configuration
- `isEnabled()` - Check if logging is enabled
## License
MIT