brw-core-logger
Version:
This is frontend logger utility which is used to log messages in the frontend application.
232 lines (179 loc) • 5.61 kB
Markdown
# Logger Utility Documentation
## Overview
The Logger utility provides a comprehensive logging solution for JavaScript/TypeScript applications with features including:
- **Log level management** (DEBUG, INFO, WARN, ERROR, SILENT)
- **Namespaced logging** for different application components
- **Performance measurement** with execution timing
- **Extensible architecture** with custom handlers
- **Visual console output** with color-coded formatting
## Installation
```bash
npm install brw-core-logger
```
## Importing
```typescript
import { Logger, LogLevel, type LogHandler, type LogEntry } from 'brw-core-logger';
```
## Basic Usage
### Creating Loggers
```typescript
// Create namespaced loggers
const apiLogger = new Logger("API");
const uiLogger = new Logger("UI", LogLevel.DEBUG);
```
### Logging Messages
```typescript
apiLogger.debug("Initializing API client");
apiLogger.info("Fetching user data", { userId: 123 });
uiLogger.warn("Deprecated component used");
apiLogger.error("API request failed", new Error("Connection timeout"));
```
## Log Levels
| Level | Value | Description |
|---------|-------|---------------------------------|
| DEBUG | 0 | Detailed diagnostic information |
| INFO | 1 | General operational messages |
| WARN | 2 | Potential issues |
| ERROR | 3 | Runtime errors |
| SILENT | 4 | Suppress all logging |
### Configuring Levels
```typescript
// Set global log level
Logger.setGlobalLevel(LogLevel.DEBUG);
// Set instance-specific level
uiLogger.setLevel(LogLevel.WARN);
```
## Performance Measurement
### Timing Operations
```typescript
// Start timer
const endTimer = uiLogger.startTimer("Rendering dashboard");
// ... perform operations ...
// End timer and log duration
endTimer();
```
### Measuring Function Execution
```typescript
// Measure synchronous function
const result = await apiLogger.measure(
() => processData(largeDataset),
"Data processing",
{ datasetSize: largeDataset.length }
);
// Measure asynchronous function
const userData = await apiLogger.measure(
async () => fetchUserData(userId),
"API user fetch",
{ userId }
);
```
## Advanced Features
### Custom Handlers
```typescript
// Create error reporting handler
const errorReporter: LogHandler = (entry) => {
if (entry.level === LogLevel.ERROR) {
sendToErrorTrackingService(entry);
}
};
// Add global handler
Logger.addHandler(errorReporter);
// Create localStorage logger
const storageLogger: LogHandler = (entry) => {
if (entry.level >= LogLevel.INFO) {
const logs = JSON.parse(localStorage.getItem("app-logs") || "[]");
logs.push(entry);
localStorage.setItem("app-logs", JSON.stringify(logs));
}
};
// Add to specific logger instance
const storageLoggerInstance = new Logger("Storage");
storageLoggerInstance.addHandler(storageLogger);
```
### Removing Handlers
```typescript
Logger.removeHandler(errorReporter);
```
## API Reference
### Logger Class
#### Constructor
```typescript
new Logger(name: string, level?: LogLevel)
```
- `name`: Namespace identifier
- `level`: Optional log level (default: global level)
#### Methods
| Method | Parameters | Description |
|--------|------------|-------------|
| `debug` | `message: string, data?: any` | Log debug message |
| `info` | `message: string, data?: any` | Log info message |
| `warn` | `message: string, data?: any` | Log warning |
| `error` | `message: string, data?: any` | Log error |
| `setLevel` | `level: LogLevel` | Set instance log level |
| `getLevel` | `none` | Get current log level |
| `startTimer` | `message: string, data?: any` | Start performance timer |
| `measure` | `fn: Function, message: string, data?: any` | Measure function execution |
### Static Methods
| Method | Parameters | Description |
|--------|------------|-------------|
| `setGlobalLevel` | `level: LogLevel` | Set global log level |
| `addHandler` | `handler: LogHandler` | Add global log handler |
| `removeHandler` | `handler: LogHandler` | Remove global handler |
### Interfaces
#### LogEntry
```typescript
interface LogEntry {
timestamp: Date;
level: LogLevel;
name: string;
message: string;
data?: any;
duration?: number;
}
```
#### LogHandler
```typescript
type LogHandler = (entry: LogEntry) => void;
```
## Best Practices
1. **Namespace Organization**:
```typescript
// Recommended naming convention
const apiLogger = new Logger("API:UserService");
const authLogger = new Logger("Auth:OAuthHandler");
```
2. **Production Configuration**:
```typescript
// Set appropriate levels for production
if (process.env.NODE_ENV === "production") {
Logger.setGlobalLevel(LogLevel.WARN);
}
```
3. **Error Handler**:
```typescript
// Centralized error handling
window.addEventListener("error", (event) => {
appLogger.error("Unhandled error", event.error);
});
```
4. **Performance Critical Sections**:
```typescript
// Measure critical operations
const processResults = await analyticsLogger.measure(
() => processAnalyticsData(data),
"Analytics processing",
{ records: data.length }
);
```
## Example Output

*Sample console output showing color-coded log messages with namespaces and performance timing*
## Browser Support
The Logger utility supports all modern browsers including:
- Chrome 50+
- Firefox 45+
- Safari 10+
- Edge 15+
- Node.js 14+
## License
MIT License. Free for commercial and personal use.