Skip to content

Log-Based Alerting — Creating Alerts from Log Patterns

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Log Based Alerting. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Log-based alerting triggers notifications when specific log patterns, rates, or thresholds are detected in aggregated log data.

// Log pattern alert engine
class LogAlertEngine {
  constructor() {
    this.rules = [];
    this.alertCounters = new Map();
  }

  addRule(rule) {
    this.rules.push({
      name: rule.name,
      pattern: new RegExp(rule.pattern, 'i'),
      timeWindow: rule.timeWindow || 60000,
      threshold: rule.threshold || 1,
      level: rule.level || 'warning',
      channels: rule.channels || ['slack'],
      enabled: rule.enabled !== false
    });
  }

  async evaluate(logEntry) {
    for (const rule of this.rules) {
      if (!rule.enabled) continue;
      if (!rule.pattern.test(logEntry.message || '')) continue;

      const counterKey = `${rule.name}:${this.getTimeBucket(logEntry.timestamp, rule.timeWindow)}`;
      const count = (this.alertCounters.get(counterKey) || 0) + 1;
      this.alertCounters.set(counterKey, count);

      if (count === rule.threshold) {
        await this.triggerAlert(rule, logEntry, count);
      }
    }
  }

  getTimeBucket(timestamp, windowMs) {
    const time = new Date(timestamp).getTime();
    return Math.floor(time / windowMs);
  }

  async triggerAlert(rule, logEntry, count) {
    const alert = {
      name: rule.name,
      level: rule.level,
      message: `Alert triggered: ${rule.name} - ${count} matches in ${rule.timeWindow / 1000}s`,
      sample: logEntry,
      count,
      timestamp: new Date().toISOString()
    };

    for (const channel of rule.channels) {
      await this.sendAlert(channel, alert);
    }

    // Cleanup old counters
    this.cleanupOldCounters();
  }

  async sendAlert(channel, alert) {
    switch (channel) {
      case 'slack':
        await slackClient.send({
          channel: '#alerts',
          text: `*${alert.level.toUpperCase()}*: ${alert.message}`
        });
        break;
      case 'pagerduty':
        await pagerDuty.triggerIncident(alert);
        break;
    }
  }

  cleanupOldCounters() {
    const cutoff = Date.now() - 300000; // 5 min
    for (const [key, _] of this.alertCounters) {
      const timestamp = parseInt(key.split(':')[1]) * 60000;
      if (timestamp < cutoff) this.alertCounters.delete(key);
    }
  }
}

Log-based alerting enables detection of patterns like repeated error codes, slow query spikes, and security intrusion attempts.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro