log-coolector
v1.0.1
Published
A TypeScript/JavaScript client library for sending logs and metrics to System Monitoring platform
Maintainers
Readme
log-coolector
A TypeScript/JavaScript client library for sending logs and metrics to monitoring platforms with automatic environment detection and comprehensive error handling.
Installation
npm install log-coolectorQuick Start
import { LogCollector } from 'log-coolector'
// Initialize the client with API key (production/staging)
const logger = new LogCollector({
apiKey: 'sm_your-api-key-here', // API key with 'sm_' prefix
baseUrl: 'https://your-monitoring-server.com'
})
// Or use in development mode (logs to console)
const devLogger = new LogCollector() // Auto-detects development environment
// Log messages with different levels
await logger.info('Application started successfully')
await logger.warn('High memory usage detected', { memoryUsage: '85%' })
await logger.error('Database connection failed', new Error('Connection timeout'))
// Send custom log entries with metadata
await logger.log({
level: 'INFO',
message: 'User action completed',
category: 'APPLICATION',
metadata: {
userId: 'user-123',
action: 'profile-update',
timestamp: new Date().toISOString()
}
})
// Business events tracking
await logger.businessEvent('user_registration', {
userId: 'user-456',
registrationMethod: 'email',
source: 'landing-page'
})
// API request monitoring
await logger.apiRequest('/api/users', 'POST', 201, 245, {
userAgent: 'Mozilla/5.0...',
ip: '192.168.1.1'
})Configuration
Environment Detection
log-coolector automatically detects your environment:
- Development: Logs to console only (when
NODE_ENV=developmentor no API key provided) - Production/Staging: Sends logs to monitoring server (when API key provided)
Required Options (Production)
apiKey: Your API key with 'sm_' prefix for authenticationbaseUrl: The base URL of your monitoring server
Optional Options
serverId: Identifier for the server/instance (default: auto-generated)source: Source identifier for logs (default: 'unknown')defaultCategory: Default log category (default: 'APPLICATION')timeout: HTTP request timeout in ms (default: 5000)retryAttempts: Number of retry attempts for failed requests (default: 3)bufferSize: Maximum number of logs to buffer (default: 100)flushInterval: Auto-flush interval in ms (default: 30000)enableAutoFlush: Enable automatic log buffer flushing (default: true)
API Reference
Logging Methods
log(entry: LogEntry): Promise<boolean>
Send a custom log entry with full metadata control.
debug(message: string, metadata?: Record<string, any>): Promise<boolean>
Log with DEBUG level for detailed debugging information.
info(message: string, metadata?: Record<string, any>): Promise<boolean>
Log with INFO level for general information messages.
warn(message: string, metadata?: Record<string, any>): Promise<boolean>
Log with WARN level for warning messages and potential issues.
error(message: string, error?: Error, metadata?: Record<string, any>): Promise<boolean>
Log with ERROR level. Automatically extracts error details if an Error object is provided.
fatal(message: string, error?: Error, metadata?: Record<string, any>): Promise<boolean>
Log with FATAL level for critical errors that may cause application failure.
Specialized Logging
businessEvent(eventName: string, metadata?: Record<string, any>): Promise<boolean>
Track business events like user registrations, purchases, etc.
apiRequest(endpoint: string, method: string, statusCode: number, responseTime: number, metadata?: Record<string, any>): Promise<boolean>
Log API request details with performance metrics.
Buffer Management
flush(): Promise<boolean>
Manually flush all buffered logs to the monitoring server.
getBufferStatus(): { size: number, maxSize: number }
Get current buffer status for monitoring queue health.
Utility Methods
testConnection(): Promise<boolean>
Test connection to the monitoring server (returns false in development mode).
destroy(): void
Clean up resources, flush remaining logs, and stop auto-flush timers.
Log Levels
DEBUG: Detailed information for debuggingINFO: General information messagesWARN: Warning messages for potential issuesERROR: Error messages for handled errorsFATAL: Critical errors that may cause application failure
Log Categories
SYSTEM: System-level eventsAPPLICATION: Application-specific eventsDATABASE: Database-related eventsNETWORK: Network-related eventsSECURITY: Security-related eventsPERFORMANCE: Performance-related eventsMONITORING: Monitoring system events
API Key Format
API keys must use the sm_ prefix for security and validation:
- Correct:
sm_biBfxUIw1UK26yeja0LxEIxTjcjitomX5dDRlZSYmJY - Incorrect:
smon_...or any other prefix
Error Handling
The client includes built-in error handling and retry logic:
- Development Mode: Errors logged to console, no network requests
- Production Mode: Failed requests are automatically retried up to
retryAttemptstimes - Uses exponential backoff for retry delays (1s, 2s, 4s, etc.)
- Logs are buffered and can be manually flushed if needed
- Connection issues are logged to console for debugging
- Invalid API keys (wrong prefix) are caught early with clear error messages
Buffering and Auto-Flush
By default, logs are buffered and automatically flushed:
- Logs are sent in batches for better performance
- Buffer is flushed when it reaches
bufferSizelimit - Buffer is automatically flushed every
flushIntervalmilliseconds - Buffer is flushed when
destroy()is called
Disable auto-flush by setting enableAutoFlush: false to send logs immediately.
Environment-Specific Usage
Development Mode
import { LogCollector } from 'log-coolector'
// No configuration needed - auto-detects development environment
const logger = new LogCollector()
// Logs will appear in console with colored output
await logger.info('This appears in console only')
await logger.error('Development error', new Error('Test error'))Production Mode
import { LogCollector } from 'log-coolector'
const logger = new LogCollector({
apiKey: process.env.MONITORING_API_KEY, // Must start with 'sm_'
baseUrl: process.env.MONITORING_BASE_URL
})
// Logs are sent to monitoring server
await logger.info('Production log entry')TypeScript Support
The library is written in TypeScript and includes full type definitions:
import { LogCollector, LogEntry, MonitoringConfig } from 'log-coolector'
const config: MonitoringConfig = {
apiKey: 'sm_your-api-key',
baseUrl: 'https://monitoring.example.com'
}
const logger = new LogCollector(config)
const logEntry: LogEntry = {
level: 'INFO',
message: 'Test message',
category: 'APPLICATION',
metadata: {
userId: 'user-123',
feature: 'authentication'
}
}Framework Integration
Next.js API Routes
// app/api/users/route.ts
import { LogCollector } from 'log-coolector'
import { NextRequest, NextResponse } from 'next/server'
const logger = new LogCollector({
apiKey: process.env.MONITORING_API_KEY,
baseUrl: process.env.MONITORING_BASE_URL
})
export async function GET(request: NextRequest) {
try {
// Log API request
await logger.apiRequest('/api/users', 'GET', 200, 150, {
userAgent: request.headers.get('user-agent'),
ip: request.ip
})
return NextResponse.json({ users: [] })
} catch (error) {
await logger.error('API error', error as Error, {
endpoint: '/api/users',
method: 'GET'
})
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}Express.js Middleware
import express from 'express'
import { LogCollector } from 'log-coolector'
const app = express()
const logger = new LogCollector({
apiKey: process.env.MONITORING_API_KEY,
baseUrl: process.env.MONITORING_BASE_URL
})
// Request logging middleware
app.use((req, res, next) => {
const start = Date.now()
res.on('finish', () => {
const duration = Date.now() - start
logger.apiRequest(req.path, req.method, res.statusCode, duration, {
userAgent: req.get('User-Agent'),
ip: req.ip
})
})
next()
})Version History
v1.0.0 (Current)
- ✅ Automatic environment detection (dev vs production)
- ✅ API key validation with
sm_prefix requirement - ✅ Comprehensive error handling and retry logic
- ✅ Buffered logging with auto-flush capability
- ✅ TypeScript support with full type definitions
- ✅ Business event tracking and API request monitoring
- ✅ Next.js and Express.js integration examples
Contributing
- Clone the repository
- Install dependencies:
npm install - Build the library:
npm run build - Test your changes:
npm test - Update the version:
npm version patch|minor|major - Publish:
npm publish
Support
For issues and questions:
- GitHub Issues: Create an issue
- Documentation: See this README and TypeScript definitions
- Examples: Check the integration examples above
License
MIT License - see LICENSE file for details
