Configuration Guide

Learn how to configure StackSleuth for optimal performance monitoring in your application.

Core Configuration Options

All StackSleuth agents share these core configuration options:

Option Type Default Description
enabled boolean true Enable or disable the agent
projectId string required Unique identifier for your project
apiKey string null API key for authentication (required for cloud-hosted)
apiEndpoint string 'http://localhost:3000' StackSleuth API endpoint
sampleRate number 1.0 Percentage of requests to monitor (0.0-1.0)
enableTracing boolean true Enable distributed tracing
enableMetrics boolean true Enable performance metrics collection
enableProfiling boolean false Enable CPU/memory profiling (higher overhead)

Backend Agent Configuration

Additional options for backend monitoring:

const agent = new BackendAgent({
    // Core options
    enabled: true,
    projectId: 'my-backend-app',
    
    // Backend-specific options
    middleware: {
        captureBody: true,        // Capture request/response bodies
        captureHeaders: true,     // Capture HTTP headers
        redactKeys: ['password', 'token', 'secret'], // Redact sensitive data
        ignoreRoutes: ['/health', '/metrics'],       // Routes to ignore
        ignoreUserAgents: ['bot', 'crawler']         // User agents to ignore
    },
    
    // Database monitoring
    database: {
        captureQueries: true,     // Log database queries
        slowQueryThreshold: 100,  // Mark queries slower than 100ms
        explainSlowQueries: true  // Run EXPLAIN on slow queries
    },
    
    // Custom metadata
    metadata: {
        environment: 'production',
        region: 'us-west-2',
        version: '1.2.3'
    }
});
Tip: Use environment variables for sensitive configuration:
apiKey: process.env.STACKSLEUTH_API_KEY

Frontend Agent Configuration

Options specific to browser monitoring:

const agent = new FrontendAgent({
    // Core options
    enabled: true,
    projectId: 'my-frontend-app',
    
    // Frontend-specific options
    performance: {
        trackResources: true,     // Track resource loading times
        trackLongTasks: true,     // Track tasks > 50ms
        trackFCP: true,           // First Contentful Paint
        trackLCP: true,           // Largest Contentful Paint
        trackCLS: true,           // Cumulative Layout Shift
        trackFID: true,           // First Input Delay
        trackTTFB: true           // Time to First Byte
    },
    
    // Error tracking
    errors: {
        captureErrors: true,      // Capture JavaScript errors
        capturePromiseRejections: true,
        ignoreErrors: ['ResizeObserver', 'Network request failed'],
        beforeSend: (error) => {
            // Filter or modify errors before sending
            if (error.message.includes('test')) return null;
            return error;
        }
    },
    
    // User tracking
    user: {
        trackClicks: true,        // Track user clicks
        trackScrolls: true,       // Track scroll depth
        trackSessions: true,      // Track user sessions
        anonymizeIP: true         // Anonymize IP addresses
    }
});
Privacy Notice: Always inform users about monitoring and comply with privacy regulations (GDPR, CCPA).

Database Agent Configuration

Configure database-specific monitoring:

MongoDB Agent

const mongoAgent = new MongoDBAgent({
    connectionString: 'mongodb://localhost:27017',
    projectId: 'my-app',
    
    // MongoDB-specific options
    profiling: {
        slowOpThreshold: 100,     // Log operations > 100ms
        sampleRate: 0.1,          // Sample 10% of operations
        captureFullQuery: false   // Redact query values
    },
    
    collections: {
        ignore: ['sessions', 'logs'], // Collections to ignore
        indexAnalysis: true           // Analyze index usage
    }
});

Redis Agent

const redisAgent = new RedisAgent({
    host: 'localhost',
    port: 6379,
    projectId: 'my-app',
    
    // Redis-specific options
    monitoring: {
        trackKeyPatterns: true,   // Track key access patterns
        trackMemoryUsage: true,   // Monitor memory consumption
        slowLogThreshold: 10      // Commands slower than 10ms
    }
});

MySQL Agent

const mysqlAgent = new MySQLAgent({
    host: 'localhost',
    user: 'monitoring',
    password: process.env.DB_PASSWORD,
    projectId: 'my-app',
    
    // MySQL-specific options
    monitoring: {
        slowQueryLog: true,       // Enable slow query logging
        slowQueryThreshold: 100,  // Queries slower than 100ms
        explainPlan: true,        // Get execution plans
        indexUsage: true          // Track index effectiveness
    }
});

Environment-Specific Configuration

Configure StackSleuth differently for each environment:

// config/stacksleuth.js
const configs = {
    development: {
        enabled: true,
        sampleRate: 1.0,          // Monitor all requests in dev
        apiEndpoint: 'http://localhost:3000',
        enableProfiling: true     // Enable profiling in dev
    },
    
    staging: {
        enabled: true,
        sampleRate: 0.5,          // Monitor 50% in staging
        apiEndpoint: 'https://staging-api.stacksleuth.com',
        enableProfiling: false
    },
    
    production: {
        enabled: true,
        sampleRate: 0.1,          // Monitor 10% in production
        apiEndpoint: 'https://api.stacksleuth.com',
        enableProfiling: false,
        apiKey: process.env.STACKSLEUTH_API_KEY
    }
};

export default configs[process.env.NODE_ENV || 'development'];

Performance Thresholds

Set custom thresholds for performance monitoring:

const agent = new BackendAgent({
    projectId: 'my-app',
    
    thresholds: {
        // Response time thresholds (ms)
        responseTime: {
            good: 200,      // < 200ms is good
            warning: 1000,  // 200-1000ms is warning
            critical: 3000  // > 3000ms is critical
        },
        
        // Error rate thresholds (percentage)
        errorRate: {
            good: 0.01,     // < 1% is good
            warning: 0.05,  // 1-5% is warning
            critical: 0.10  // > 10% is critical
        },
        
        // Database query thresholds (ms)
        databaseQuery: {
            good: 50,
            warning: 200,
            critical: 1000
        },
        
        // Memory usage thresholds (MB)
        memoryUsage: {
            good: 256,
            warning: 512,
            critical: 1024
        }
    }
});

Advanced Configuration

Custom Reporters

class CustomReporter {
    async report(metrics) {
        // Send metrics to custom endpoint
        await fetch('https://my-metrics-service.com', {
            method: 'POST',
            body: JSON.stringify(metrics)
        });
    }
}

const agent = new BackendAgent({
    projectId: 'my-app',
    reporters: [
        new CustomReporter(),
        new ConsoleReporter({ pretty: true })
    ]
});

Sampling Strategies

// Adaptive sampling based on traffic
const agent = new BackendAgent({
    projectId: 'my-app',
    sampling: {
        type: 'adaptive',
        baseRate: 0.01,           // 1% baseline
        peakRate: 0.10,           // 10% during peaks
        errorRate: 1.0,           // 100% for errors
        slowRequestRate: 0.50     // 50% for slow requests
    }
});

Custom Instrumentation

// Add custom timers
agent.startTimer('custom-operation');
// ... perform operation ...
agent.endTimer('custom-operation');

// Add custom metrics
agent.recordMetric('cache.hit.rate', 0.95);
agent.recordMetric('queue.length', 42);

// Add custom spans
const span = agent.startSpan('process-payment');
try {
    // ... process payment ...
    span.setTag('amount', 99.99);
    span.setTag('currency', 'USD');
} finally {
    span.finish();
}

Configuration Best Practices

  1. Start Conservative: Begin with low sample rates and increase as needed
  2. Use Environment Variables: Never hardcode sensitive values
  3. Monitor Overhead: Check the performance impact of monitoring
  4. Redact Sensitive Data: Configure proper data redaction rules
  5. Test Configuration: Validate config changes in staging first
  6. Document Changes: Keep a changelog of configuration updates
  7. Regular Review: Periodically review and optimize settings
Configuration Validation: StackSleuth validates configuration on startup and logs warnings for invalid settings.

Related Documentation