1.0.2 • Published 4 months ago

express-konnect-trace v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Express Konnect Trace

A robust API tracing and monitoring system for Express.js applications that sends detailed notifications to Slack.

Features

  • 📊 Track API requests and responses
  • 🔔 Send detailed notifications to Slack
  • 🚨 Configure different channels for different status codes
  • 📝 Include request/response data in notifications
  • ⚙️ Highly customizable configuration
  • 📈 Monitor API performance with execution time tracking
  • 🛡️ Proper error handling with stack traces

Installation

npm install express-konnect-trace

Quick Start

import express from 'express';
import { setupTracing } from 'express-konnect-trace';

const app = express();
app.use(express.json());

// Set up tracing
const { traceMiddleware, errorHandlerMiddleware } = setupTracing({
  webhookUrl: 'YOUR_SLACK_WEBHOOK_URL',
  track2xxResponses: true,  // Track successful responses
  track4xxResponses: true,  // Track client errors
  track5xxResponses: true   // Track server errors
});

// Apply middleware (before routes)
app.use(traceMiddleware);

// Define your routes
app.get('/', (req, res) => {
  res.json({ message: 'Hello World' });
});

// Apply error handler (after routes)
app.use(errorHandlerMiddleware);

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Configuration Options

The setupTracing function accepts various options to customize the tracing behavior:

setupTracing({
  // Enable/disable notifications (defaults to true)
  enableNotifications: true,
  
  // Default Slack webhook URL
  webhookUrl: 'YOUR_SLACK_WEBHOOK_URL',
  
  // Control what status codes to track
  track2xxResponses: false,  // Success responses (default: false)
  track4xxResponses: true,   // Client errors (default: true)
  track5xxResponses: true,   // Server errors (default: true)
  
  // Control what data to include
  includeBody: true,         // Include request body
  includeQuery: true,        // Include query parameters
  includeParams: true,       // Include route parameters
  includeHeaders: true,      // Include request headers
  includeStackTrace: true,   // Include stack traces for errors
  
  // Channel configuration for different status codes
  channelConfig: {
    // Default fallback channel
    default: 'https://hooks.slack.com/services/DEFAULT_URL',
    
    // Specific status code channels
    statusCodeChannels: {
      404: 'https://hooks.slack.com/services/NOT_FOUND_URL',
      500: 'https://hooks.slack.com/services/SERVER_ERROR_URL',
    },
    
    // Channel by series (2xx, 4xx, 5xx)
    seriesChannels: {
      '2xx': 'https://hooks.slack.com/services/SUCCESS_URL',
      '4xx': 'https://hooks.slack.com/services/CLIENT_ERROR_URL',
      '5xx': 'https://hooks.slack.com/services/SERVER_ERROR_URL',
    },
  },
  
  // Custom filter function
  shouldNotify: (statusCode, path) => {
    // Don't trace health check endpoints
    return !path.includes('/health');
  },
});

Notification Example

Here's what a notification looks like in Slack:

  • HTTP Status: 500 Internal Server Error
  • Message: Error connecting to database
  • Path: /api/users
  • Method: GET
  • Response Time: 42 ms
  • Stack Trace: Full error stack trace
  • Request Details: Headers, Query Params, Body (as configured)
  • Response Data: Error details

Advanced Usage

Custom Error Status Codes

You can set custom status codes on errors:

app.get('/not-found', (req, res, next) => {
  const error = new Error('Resource not found');
  error.status = 404; // Will be used as the status code
  next(error);
});

Selective Tracing

Use the shouldNotify option to selectively trace requests:

setupTracing({
  webhookUrl: 'YOUR_SLACK_WEBHOOK_URL',
  shouldNotify: (statusCode, path) => {
    // Skip tracing for health checks and specific paths
    const ignorePaths = ['/health', '/metrics', '/ping'];
    if (ignorePaths.some(p => path.includes(p))) {
      return false;
    }
    
    // Always trace 500 errors
    if (statusCode >= 500) {
      return true;
    }
    
    // Only trace 404 errors for API routes
    if (statusCode === 404) {
      return path.startsWith('/api/');
    }
    
    // Default behavior for other status codes
    return statusCode >= 400;
  }
});

License

MIT