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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@ganemchedli/telegram-error-logger

v1.0.0

Published

A comprehensive error logging package for Node.js with Telegram integration, supporting Fastify and Express

Readme

Telegram Error Logger

A comprehensive error logging package for Node.js applications with Telegram integration. Supports Fastify and Express frameworks with automatic error tracking, rate limiting, deduplication, and rich formatting.

npm version License

✨ Features

  • 🚀 Framework Support: First-class support for Fastify and Express
  • 📊 Rich Formatting: Beautiful, structured error messages with context
  • 🔒 Security: Automatic sanitization of sensitive data (passwords, tokens, etc.)
  • Rate Limiting: Prevent spam with configurable rate limits
  • 🔄 Deduplication: Avoid duplicate error notifications
  • 🎯 Error Filtering: Only send errors that matter
  • 🔧 Highly Configurable: Extensive options for customization
  • 📝 TypeScript Support: Full TypeScript definitions included
  • Well Tested: Comprehensive test coverage

📦 Installation

npm install @telegram-error-logger/core

🚀 Quick Start

Prerequisites

  1. Create a Telegram bot via @BotFather
  2. Get your bot token
  3. Get your chat ID (use @userinfobot)

Fastify Example

const fastify = require('fastify');
const telegramErrorLogger = require('@telegram-error-logger/core/src/adapters/fastify');

const app = fastify();

// Register the plugin
app.register(telegramErrorLogger, {
  botToken: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID',
  appName: 'My Fastify App',
  environment: 'production'
});

// Errors are automatically logged!
app.get('/error', async (request, reply) => {
  throw new Error('Something went wrong!');
});

app.listen({ port: 3000 });

Express Example

const express = require('express');
const createExpressMiddleware = require('@telegram-error-logger/core/src/adapters/express');

const app = express();

// Register the middleware (after routes, before error handlers)
app.use(createExpressMiddleware({
  botToken: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID',
  appName: 'My Express App',
  environment: 'production'
}));

// Errors are automatically logged!
app.get('/error', (req, res, next) => {
  next(new Error('Something went wrong!'));
});

app.listen(3000);

Standalone Usage

const TelegramErrorLogger = require('@telegram-error-logger/core');

const logger = new TelegramErrorLogger({
  botToken: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID',
  appName: 'My App'
});

// Send errors
try {
  // Your code
} catch (error) {
  await logger.sendError(error, {
    userId: '123',
    action: 'processing payment'
  });
}

// Send custom messages
await logger.sendCustomMessage('Deployment completed!', {
  level: 'success',
  data: { version: '1.2.3' }
});

📖 Configuration Options

Core Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | botToken | string | required | Telegram bot token | | chatId | string | required | Telegram chat ID | | appName | string | 'Application' | Your application name | | environment | string | 'production' | Environment (dev, staging, prod) | | enableStackTrace | boolean | true | Include stack traces in errors | | maxStackTraceLines | number | 10 | Max stack trace lines to include |

Framework-Specific Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | includeHeaders | boolean | false | Include request headers | | includeBody | boolean | true | Include request body | | excludeRoutes | string[] | [] | Routes to exclude from logging | | errorFilter | function | null | Filter function for errors | | extractUser | function | null | Extract user from request | | contextExtractor | function | null | Extract custom context |

Advanced Options

| Option | Type | Default | Description | |--------|------|---------|-------------| | rateLimitWindow | number | 60000 | Rate limit window (ms) | | rateLimitMax | number | 10 | Max errors per window | | deduplicate | boolean | false | Enable deduplication | | deduplicateWindow | number | 300000 | Deduplication window (ms) | | retryAttempts | number | 3 | Retry attempts for sending |

🎯 Advanced Usage

Error Filtering

Only send server errors (5xx):

app.register(telegramErrorLogger, {
  botToken: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID',
  errorFilter: (error) => {
    return !error.statusCode || error.statusCode >= 500;
  }
});

User Extraction

Extract user information from requests:

app.register(telegramErrorLogger, {
  botToken: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID',
  extractUser: (request) => {
    return {
      id: request.user?.id,
      email: request.user?.email
    };
  }
});

Custom Context

Add custom context to errors:

app.register(telegramErrorLogger, {
  botToken: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID',
  contextExtractor: (request) => {
    return {
      requestId: request.id,
      userAgent: request.headers['user-agent'],
      correlationId: request.headers['x-correlation-id']
    };
  }
});

Rate Limiting

Prevent spam during error storms:

app.register(telegramErrorLogger, {
  botToken: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID',
  rateLimitWindow: 60000, // 1 minute
  rateLimitMax: 5 // Max 5 errors per minute
});

Deduplication

Avoid duplicate notifications:

app.register(telegramErrorLogger, {
  botToken: 'YOUR_BOT_TOKEN',
  chatId: 'YOUR_CHAT_ID',
  deduplicate: true,
  deduplicateWindow: 300000 // 5 minutes
});

Manual Logging (Fastify)

// Access the logger instance
app.get('/manual', async (request, reply) => {
  try {
    await riskyOperation();
  } catch (error) {
    // Manual error logging with custom context
    await app.telegramLogger.sendError(error, {
      custom: {
        operation: 'riskyOperation',
        retryCount: 3
      }
    });
    throw error;
  }
});

// Send custom notifications
app.post('/deploy', async (request, reply) => {
  await app.telegramLogger.sendCustomMessage(
    'New deployment started',
    {
      level: 'info',
      title: 'Deployment',
      data: {
        version: request.body.version,
        user: request.user.email
      }
    }
  );
});

Route-Level Error Handlers (Fastify)

app.post('/critical', {
  errorHandler: async (error, request, reply) => {
    // Custom handling for this specific route
    await app.telegramLogger.sendError(error, {
      custom: {
        criticalRoute: true,
        priority: 'high'
      }
    });
    
    reply.status(500).send({ error: 'Critical error occurred' });
  }
}, async (request, reply) => {
  // Route handler
});

📋 Message Levels

Custom messages support different severity levels:

  • info ℹ️ - Informational messages
  • success ✅ - Success notifications
  • warning ⚠️ - Warning messages
  • error ❌ - Error messages
  • critical 🔥 - Critical alerts
  • debug 🐛 - Debug information
  • alert 🚨 - Important alerts
await logger.sendCustomMessage('Database backup completed', {
  level: 'success',
  data: { size: '2.5GB', duration: '45s' }
});

🔒 Security

The logger automatically sanitizes sensitive data:

  • Passwords: Any field named password, pwd, secret
  • Tokens: token, apiKey, api_key, authorization
  • Headers: authorization, cookie, x-api-key, x-auth-token

All sensitive fields are replaced with [REDACTED].

🧪 Testing

# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Watch mode
npm run test:watch

📝 Examples

Check the examples/ directory for complete working examples:

  • examples/fastify-example.js - Comprehensive Fastify integration
  • examples/express-example.js - Complete Express setup

Run examples:

# Copy .env.example to .env and add your credentials
cp .env.example .env

# Run Fastify example
npm run example:fastify

# Run Express example
npm run example:express

🏗️ Project Structure

telegram-error-logger/
├── src/
│   ├── index.js                 # Main TelegramErrorLogger class
│   ├── formatters/
│   │   ├── errorFormatter.js    # Error message formatting
│   │   └── messageFormatter.js  # Custom message formatting
│   ├── adapters/
│   │   ├── fastify.js          # Fastify plugin
│   │   └── express.js          # Express middleware
│   ├── utils/
│   │   └── telegram.js         # Telegram API client
│   └── index.d.ts              # TypeScript definitions
├── tests/                       # Test files
├── examples/                    # Usage examples
└── package.json

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT

🙏 Acknowledgments

Built with:

📞 Support


Made with ❤️ for better error monitoring