UNPKG

@seawingai/winglog

Version:

A powerful TypeScript/JavaScript logging library built on top of Pino for structured logging with enhanced features

359 lines (262 loc) โ€ข 9.07 kB
# WingLog [![npm version](https://badge.fury.io/js/@seawingai%2Fwinglog.svg)](https://badge.fury.io/js/@seawingai%2Fwinglog) [![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) A powerful TypeScript/JavaScript logging library built on top of Pino for structured logging with enhanced features. WingLog provides a simple and intuitive API for logging with automatic file output, console formatting, and performance tracking. ## Features - ๐Ÿ“ **Structured logging** with Pino under the hood - ๐ŸŽจ **Beautiful console output** with pino-pretty formatting - ๐Ÿ’พ **Automatic file logging** to `logs/` directory - โฑ๏ธ **Performance tracking** with duration measurements - ๐Ÿท๏ธ **Named loggers** for organized logging - ๐ŸŽฏ **TypeScript support** with full type definitions - ๐Ÿงช **Comprehensive testing** with Jest ## Installation ```bash npm install @seawingai/winglog # or pnpm add @seawingai/winglog # or yarn add @seawingai/winglog ``` ## Quick Start ```typescript import { WingLog } from '@seawingai/winglog'; // Create a logger instance const logger = new WingLog('my-app'); // Basic logging logger.info('Application started'); logger.success('User login successful'); logger.warn('High memory usage detected'); logger.failed('Database connection failed'); // Performance tracking const startTime = Date.now(); // ... do some work ... logger.finished('Task completed', startTime); ``` ## Usage ### Creating a Logger ```typescript import { WingLog } from '@seawingai/winglog'; // Create a named logger const logger = new WingLog('my-service'); // The logger automatically creates a logs/ directory // and saves logs to logs/my-service.log ``` ### Basic Logging ```typescript const logger = new WingLog('example'); // Information logging logger.info('This is an informational message'); // Success logging logger.success('Operation completed successfully'); // Warning logging logger.warn('This is a warning message'); // Error logging logger.failed('Operation failed'); // Debug logging logger.debug('Debug information'); // Start/Finish logging logger.started('Starting process'); logger.finished('Process completed'); ``` ### Performance Tracking ```typescript const logger = new WingLog('performance'); // Track execution time const startTime = Date.now(); // ... perform some operation ... // Log with duration const duration = logger.finished('Operation completed', startTime); console.log(`Operation took ${duration} seconds`); ``` ### Structured Logging ```typescript const logger = new WingLog('api'); // Log with additional data logger.info('User request received', { userId: 123, endpoint: '/api/users', method: 'GET' }); logger.debug('Database query executed', { query: 'SELECT * FROM users', duration: 45, rows: 100 }); logger.failed('Authentication failed', { userId: 123, reason: 'Invalid token', ip: '192.168.1.1' }); logger.warn('High memory usage detected', { memoryUsage: '85%', threshold: '80%', available: '2.5GB' }); logger.success('User created successfully', { userId: 456, email: 'newuser@example.com', role: 'user' }); logger.started('Job processing started', { jobId: 'job-123', priority: 'high' }); logger.finished('Job processing finished', { jobId: 'job-123', duration: 45, status: 'completed' }); ``` ### Error Handling ```typescript const logger = new WingLog('error-handler'); try { // ... some operation that might fail ... throw new Error('Something went wrong'); } catch (error) { logger.error('Operation failed', error); } ``` ## Log Levels WingLog supports the following log levels: - **DEBUG**: Detailed debug information - **INFO**: General information messages - **SUCCESS**: Successful operations - **WARN**: Warning messages - **FAILED**: Failed operations - **STARTED**: Process start events - **FINISHED**: Process completion events ## Output Format ### Console Output WingLog uses pino-pretty for beautiful console formatting: ``` [12:34:56.789] INFO [my-app]: Application started [12:34:57.123] SUCCESS [my-app]: User login successful [12:34:58.456] WARN [my-app]: High memory usage detected [12:34:59.789] FAILED [my-app]: Database connection failed [12:34:60.123] INFO [my-app]: User request received {"userId":123,"endpoint":"/api/users","method":"GET"} [12:34:61.456] DEBUG [my-app]: Database query executed {"query":"SELECT * FROM users","duration":45,"rows":100} ``` ### File Output Logs are automatically saved to `logs/{logger-name}.log` in JSON format for easy parsing: ```json {"level":30,"time":"2024-01-15T12:34:56.789Z","msg":"[my-app]: Application started"} {"level":30,"time":"2024-01-15T12:34:57.123Z","msg":"[my-app]: User login successful"} {"level":30,"time":"2024-01-15T12:34:60.123Z","msg":"[my-app]: User request received {\"userId\":123,\"endpoint\":\"/api/users\",\"method\":\"GET\"}"} {"level":20,"time":"2024-01-15T12:34:61.456Z","msg":"[my-app]: Database query executed {\"query\":\"SELECT * FROM users\",\"duration\":45,\"rows\":100}"} ``` ## API Reference ### WingLog Class #### Constructor ```typescript new WingLog(name: string) ``` #### Instance Methods ##### Basic Logging - `info(message: string, startTime?: number): number` - `info(message: string, rec: Record<string, any>): void` - `success(message: string, startTime?: number): number` - `success(message: string, rec: Record<string, any>): void` - `warn(message: string, startTime?: number): number` - `warn(message: string, rec: Record<string, any>): void` - `failed(message: string, startTime?: number): number` - `failed(message: string, rec: Record<string, any>): void` - `debug(message: string, startTime?: number): number` - `debug(message: string, rec: Record<string, any>): void` ##### Process Tracking - `started(message: string, startTime?: number): number` - `started(message: string, rec: Record<string, any>): void` - `finished(message: string, startTime?: number): number` - `finished(message: string, rec: Record<string, any>): void` ##### Error Handling - `error(message: string, err: unknown): void` ### LogType Enum ```typescript enum LogType { FAILED = 'FAILED', WARN = 'WARN', DEBUG = 'DEBUG', SUCCESS = 'SUCCESS', STARTED = 'STARTED', FINISHED = 'FINISHED', INFO = 'INFO', } ``` ## Examples ### Web Application Logging ```typescript import { WingLog } from '@seawingai/winglog'; const logger = new WingLog('web-app'); // Request logging app.use((req, res, next) => { const startTime = Date.now(); logger.info('HTTP Request', { method: req.method, url: req.url, userAgent: req.get('User-Agent'), ip: req.ip }); res.on('finish', () => { logger.finished(`HTTP ${req.method} ${req.url} - ${res.statusCode}`, startTime); }); next(); }); ``` ### Database Operations ```typescript const logger = new WingLog('database'); async function createUser(userData: any) { const startTime = Date.now(); try { logger.started('Creating new user'); const user = await db.users.create(userData); logger.success('User created successfully', { userId: user.id, email: user.email }); return user; } catch (error) { logger.error('Failed to create user', error); throw error; } finally { logger.finished('User creation process', startTime); } } ``` ### Background Job Processing ```typescript const logger = new WingLog('job-processor'); async function processJob(jobId: string) { const startTime = Date.now(); logger.info('Starting job processing', { jobId }); try { // Process the job await processJobData(jobId); logger.success(`Job ${jobId} processed successfully`); } catch (error) { logger.failed(`Job ${jobId} failed`, { jobId, error: error.message }); } finally { logger.finished(`Job ${jobId} processing`, startTime); } } ``` ## Configuration WingLog automatically configures itself with sensible defaults: - **Log Level**: `debug` (logs everything) - **Console Output**: Pretty-printed with colors - **File Output**: JSON format in `logs/` directory - **Timestamp Format**: ISO 8601 ## Contributing We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. ## License This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details. ## Support - ๐Ÿ“– [Documentation](https://seawingai.com/winglog) - ๐Ÿ› [Report Issues](https://github.com/seawingai/winglog/issues) - ๐Ÿ’ฌ [Discussions](https://github.com/seawingai/winglog/discussions) --- Made with โค๏ธ by [SeaWingAI](https://seawingai.com)