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

@checklogs/node-sdk

v1.0.2

Published

Official Node.js SDK for CheckLogs.dev - Log monitoring system

Readme

@checklogs/node-sdk

Official Node.js SDK for CheckLogs.dev - A powerful log monitoring system.

Installation

npm install @checklogs/node-sdk

Quick Start Setup

For a guided setup, you can use our quick-start script:

npx @checklogs/node-sdk quick-start

This will:

  • Detect your project type (CommonJS or ES Modules)
  • Create appropriate test files
  • Set up a basic configuration
  • Provide next steps to get you started

Quick Start

CommonJS (require)

const { createLogger } = require('@checklogs/node-sdk');

// Create a logger instance
const logger = createLogger('your-api-key-here');

// Log messages
await logger.info('Application started');
await logger.error('Something went wrong', { error_code: 500 });

ES Modules (import)

import { createLogger } from '@checklogs/node-sdk';

// Create a logger instance
const logger = createLogger('your-api-key-here');

// Log messages
await logger.info('Application started');
await logger.error('Something went wrong', { error_code: 500 });

Note: The SDK supports both CommonJS and ES modules. Use the import/export syntax you prefer!

Module Support

This package supports both CommonJS and ES modules:

  • CommonJS: Use require() syntax - works in traditional Node.js projects
  • ES Modules: Use import/export syntax - works in modern Node.js projects with "type": "module" in package.json or .mjs files

The package automatically provides the correct format based on how you import it.

Features

  • ✅ Full API coverage (logging, retrieval, statistics)
  • ✅ Dual package support (CommonJS & ES Modules)
  • ✅ TypeScript support with complete type definitions
  • ✅ Automatic retry mechanism with exponential backoff
  • ✅ Enhanced logging with metadata (hostname, process info, timestamps)
  • ✅ Console output integration
  • ✅ Child loggers with inherited context
  • ✅ Statistics and analytics
  • ✅ Error handling with custom error types
  • ✅ Validation and sanitization

API Overview

Basic Client

CommonJS:

const { CheckLogsClient } = require('@checklogs/node-sdk');

const client = new CheckLogsClient('your-api-key');

ES Modules:

import { CheckLogsClient } from '@checklogs/node-sdk';

const client = new CheckLogsClient('your-api-key');

Usage:

// Send a log
await client.log({
  message: 'User logged in',
  level: 'info',
  context: { user_id: 123, ip: '192.168.1.1' }
});

// Retrieve logs
const logs = await client.getLogs({
  limit: 100,
  level: 'error',
  since: '2024-01-01'
});

Enhanced Logger

CommonJS:

const { CheckLogsLogger } = require('@checklogs/node-sdk');

ES Modules:

import { CheckLogsLogger } from '@checklogs/node-sdk';

Usage:

const logger = new CheckLogsLogger('your-api-key', {
  source: 'my-app',
  defaultContext: { version: '1.0.0' },
  consoleOutput: true
});

// Convenience methods
await logger.info('Info message');
await logger.warning('Warning message');
await logger.error('Error message');
await logger.critical('Critical message');
await logger.debug('Debug message');

Configuration Options

Client Options

const client = new CheckLogsClient('api-key', {
  timeout: 5000,           // Request timeout in ms
  validatePayload: true    // Validate data before sending
});

Logger Options

const logger = new CheckLogsLogger('api-key', {
  // Client options
  timeout: 5000,
  validatePayload: true,
  
  // Logger-specific options
  source: 'my-app',                    // Default source
  user_id: 123,                        // Default user ID
  defaultContext: { env: 'prod' },     // Default context
  silent: false,                       // Suppress all output
  consoleOutput: true,                 // Also log to console
  enabledLevels: ['info', 'error'],    // Only these levels
  includeTimestamp: true,              // Add timestamp to context
  includeHostname: true                // Add hostname to context
});

Advanced Features

Child Loggers

Create child loggers with inherited context:

const mainLogger = new CheckLogsLogger('api-key', {
  defaultContext: { service: 'api' }
});

const userLogger = mainLogger.child({ module: 'user' });
const orderLogger = mainLogger.child({ module: 'orders' });

// Each child inherits parent context
await userLogger.info('User created');  // Context: { service: 'api', module: 'user' }
await orderLogger.error('Order failed'); // Context: { service: 'api', module: 'orders' }

Timing Logs

Measure execution time:

const endTimer = logger.time('db-query', 'Executing database query');

// ... your code here ...

const duration = endTimer(); // Automatically logs end time with duration
console.log(`Operation took ${duration}ms`);

Statistics and Analytics

// Get basic statistics
const stats = await client.stats.getStats();
console.log('Total logs:', stats.data.total_logs);

// Get analytics summary
const summary = await client.stats.getSummary();
console.log('Error rate:', summary.data.analytics.error_rate);

// Get specific metrics
const errorRate = await client.stats.getErrorRate();
const trend = await client.stats.getTrend();
const peakDay = await client.stats.getPeakDay();

Error Handling

The SDK provides specific error types:

const { ApiError, NetworkError, ValidationError } = require('@checklogs/node-sdk');

try {
  await logger.log({ /* invalid data */ });
} catch (error) {
  if (error instanceof ValidationError) {
    console.log('Validation failed:', error.message);
  } else if (error instanceof ApiError) {
    console.log('API error:', error.statusCode, error.message);
    
    if (error.isAuthError()) {
      console.log('Authentication problem');
    } else if (error.isRateLimitError()) {
      console.log('Rate limit exceeded');
    }
  } else if (error instanceof NetworkError) {
    console.log('Network problem:', error.message);
    
    if (error.isTimeoutError()) {
      console.log('Request timed out');
    }
  }
}

Retry Mechanism

The logger automatically retries failed requests:

// Check retry queue status
const status = logger.getRetryQueueStatus();
console.log(`${status.count} logs pending retry`);

// Wait for all logs to be sent
const success = await logger.flush(30000); // 30 second timeout
if (success) {
  console.log('All logs sent successfully');
}

// Clear retry queue if needed
logger.clearRetryQueue();

Log Levels

Supported log levels (in order of severity):

  • debug - Development and troubleshooting information
  • info - General application flow
  • warning - Potentially harmful situations
  • error - Error events that might still allow the application to continue
  • critical - Very severe error events that might cause the application to abort

Data Validation

The SDK automatically validates and sanitizes data:

  • Message: Required, max 1024 characters
  • Level: Must be valid level, defaults to 'info'
  • Source: Max 100 characters
  • Context: Objects only, max 5000 characters when serialized
  • User ID: Must be a number

Rate Limiting and Best Practices

  1. Batch Operations: Use child loggers for related operations
  2. Level Filtering: Only enable necessary log levels in production
  3. Context Size: Keep context objects reasonably small
  4. Error Handling: Always handle potential network issues
  5. Graceful Shutdown: Call flush() before app termination

TypeScript Support

Full TypeScript definitions are included:

import { CheckLogsLogger, LogLevel, LogData } from '@checklogs/node-sdk';

const logger = new CheckLogsLogger('api-key');

const logData: LogData = {
  message: 'User action',
  level: 'info',
  context: { userId: 123 }
};

await logger.log(logData);

Examples

Express.js Middleware

CommonJS version:

const express = require('express');
const { createLogger } = require('@checklogs/node-sdk');

const app = express();
const logger = createLogger('your-api-key');

// Request logging middleware
app.use((req, res, next) => {
  const requestLogger = logger.child({
    request_id: Math.random().toString(36),
    method: req.method,
    url: req.url
  });
  
  req.logger = requestLogger;
  next();
});

// Route handler
app.get('/users/:id', async (req, res) => {
  try {
    req.logger.info('Fetching user', { user_id: req.params.id });
    
    // ... your logic here ...
    
    req.logger.info('User fetched successfully');
    res.json({ user: userData });
  } catch (error) {
    req.logger.error('Failed to fetch user', { 
      error: error.message,
      stack: error.stack 
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});

ES Modules version:

import express from 'express';
import { createLogger } from '@checklogs/node-sdk';

const app = express();
const logger = createLogger('your-api-key');

// ... rest of the code is identical ...

Cron Job Monitoring

const { createLogger } = require('@checklogs/node-sdk');

const logger = createLogger('your-api-key', {
  source: 'cron-job',
  defaultContext: { job: 'daily-cleanup' }
});

async function dailyCleanup() {
  const endTimer = logger.time('cleanup', 'Starting daily cleanup');
  
  try {
    logger.info('Cleanup started');
    
    // ... cleanup logic ...
    
    logger.info('Cleanup completed successfully', { 
      records_cleaned: 1500,
      duration_ms: endTimer()
    });
  } catch (error) {
    logger.critical('Cleanup failed', { 
      error: error.message,
      duration_ms: endTimer()
    });
    throw error;
  }
}

License

MIT License - see LICENSE file for details.

Support