npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

log-coolector

v1.0.1

Published

A TypeScript/JavaScript client library for sending logs and metrics to System Monitoring platform

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-coolector

Quick 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=development or 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 authentication
  • baseUrl: 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 debugging
  • INFO: General information messages
  • WARN: Warning messages for potential issues
  • ERROR: Error messages for handled errors
  • FATAL: Critical errors that may cause application failure

Log Categories

  • SYSTEM: System-level events
  • APPLICATION: Application-specific events
  • DATABASE: Database-related events
  • NETWORK: Network-related events
  • SECURITY: Security-related events
  • PERFORMANCE: Performance-related events
  • MONITORING: 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 retryAttempts times
  • 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 bufferSize limit
  • Buffer is automatically flushed every flushInterval milliseconds
  • 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

  1. Clone the repository
  2. Install dependencies: npm install
  3. Build the library: npm run build
  4. Test your changes: npm test
  5. Update the version: npm version patch|minor|major
  6. 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