# Alerts Guide

      Set up intelligent, rule-based alerts to monitor your application logs and get notified when specific conditions are met. Trailonix alerts help you stay ahead of issues by providing real-time notifications for critical events, errors, and business metrics.

      ## Getting Started with Alerts

      Navigate to **"Alert Rules"** in the Administration section to view, create, and manage your alert rules. You can see your current rule usage in the top bar (e.g., "0 of 100 enabled rules").

      ## Creating an Alert Rule

      Click the **"+ Rule"** button to create a new alert. Every alert rule consists of several key components that work together to determine when and how you'll be notified.

      ### 1. Alert Information

      **Name** (Required): Give your alert a descriptive name that clearly identifies what it monitors.
      - ✅ Good: "Failed Login Attempts - Admin Users"
      - ✅ Good: "High Error Rate - Payment Processing"
      - ❌ Avoid: "Alert 1" or generic names

      **Tenant** (Required): Select the tenant (application environment) you want to monitor.

      ### 2. Trigger Condition

      #### Event Type (Required)
      **Every alert must start with an event type.** This is the foundation of your alert rule.

      Enter or select the event type you want to monitor:
      - Type directly: `user_login`, `payment_failed`, `error_occurred`
      - Or select from existing event types in your tenant

      > **💡 Pro Tip:** Use consistent event type naming for reliable alerts. If your app sometimes logs `userLogin` and sometimes `user_login`, your alerts may miss events.

      #### Field Matching (Optional)
      Add additional conditions to filter your events using standard log fields:

      **Available Fields:**
      - **UserId**: Match specific users or user patterns
      - **IpAddress**: Monitor events from specific IP addresses
      - **Resource**: Filter by affected resources
      - **UserAgent**: Track events from specific clients or browsers

      **Match Value**: Enter the exact value to match (supports only equal-to matching)

      Example: Set **Match Field** to "UserId" and **Match Value** to "admin_user_123" to only monitor events from that specific user.

      #### Metadata Conditions (Optional)
      For complex filtering, use metadata conditions with powerful dot notation support:

      **Metadata Field**: Specify the field path using dot notation:
      - Simple fields: `status`, `method`, `amount`
      - Nested objects: `user.role`, `payment.method`, `order.billing.country`
      - Deep nesting: `user.profile.settings.notifications.email`

      > **📝 Note:** Arrays are not currently supported in metadata conditions. Only object properties can be accessed using dot notation.

      **Operators Available:**
      - `==` Equal to
      - `!=` Not equal to
      - `>` Greater than
      - `<` Less than
      - `>=` Greater than or equal to
      - `<=` Less than or equal to
      - `LIKE` SQL-style pattern matching
      - `NOT LIKE` SQL-style pattern exclusion

      **LIKE Pattern Examples:**
      - `%admin%` - Contains "admin" anywhere
      - `admin%` - Starts with "admin"
      - `%admin` - Ends with "admin"
      - `%error%` - Contains "error" anywhere
      - Just like SQL LIKE queries!

      **Example Metadata Conditions:**
      ```
      user.role == "admin"
      payment.amount > 1000
      error.type LIKE "%timeout%"
      order.status != "completed"
      ```

      ### 3. Condition Types

      Choose how your alert should be triggered:

      #### Threshold (Recommended)
      Set up intelligent threshold-based alerting with time windows:

      **Threshold Count**: Number of matching events required to trigger the alert
      **Threshold Minutes**: Time window for counting events

      **Example**: "5 failed logins from admin users in 5 minutes"
      - Helps reduce noise from isolated incidents
      - Focuses on patterns and repeated issues
      - Recommended for most use cases

      #### Any
      Triggers immediately on every matching event:
      - Instant notification for each occurrence
      - Best for critical, zero-tolerance events
      - Can be noisy for frequent events

      ### 4. Urgency Levels

      #### Critical Alerts ⚠️ **Premium Feature**
      - **Sent immediately** at the time of occurrence
      - **Counts toward your premium alert limit**
      - Use sparingly for extremely urgent issues like:
        - Breaking exceptions that stop core functionality
        - Security breaches or suspicious activity
        - Payment system failures
        - Service outages

      #### Batch Process (Recommended)
      - **Sent every 5 minutes** in batches
      - **Email alerts are free** (doesn't count against premium limits)
      - **SMS alerts still count as premium** (same as critical alerts)
      - Condenses multiple alerts to reduce notification fatigue
      - Perfect for monitoring, warnings, and general notifications

      > **💰 Cost Tip:** Batch alerts are free for email regardless of volume, making them ideal for most monitoring needs. Save critical alerts for truly urgent situations.

      ### 5. Suppression Settings

      **Suppression Minutes**: Prevents duplicate notifications for the same rule within the specified time period.

      **How Suppression Works:**
      1. First trigger → Alert sent
      2. Subsequent triggers within suppression window → **Not sent** but still logged
      3. All triggers appear in the "Alerts" section regardless of suppression

      **Suppression Limits by Subscription:**
      - Your minimum suppression time depends on your subscription tier
      - Consider longer suppression (15-30 minutes) for non-critical issues
      - Try to avoid alert fatigue

      **Example**: With 10-minute suppression, if the same rule triggers 5 times in 8 minutes, you'll only receive 1 notification, but see all 5 events in your alerts dashboard.

      ### 6. Actions - Getting Notified

      Configure how and where you want to receive alerts. **There's no limit to the number of actions per rule.**

      #### Email Alerts
      - **Always available** for any email address
      - **Free** for batch alerts, premium for critical alerts
      - **Reliable delivery** with unsubscribe options

      **Target**: Enter any valid email address
      **Unsubscribe Management**:
      - Unsubscribe from specific alerts in "My User Settings"
      - Click "Unsubscribe" links in alert emails
      - Per-alert unsubscribe (won't affect other alerts)

      #### SMS Alerts ⚠️ **Premium Feature**
      SMS alerts require special setup and consent:

      **Requirements for SMS:**
      1. **Target must be registered** in the Trailonix system
      2. **SMS consent must be granted** in "My User Settings"
      3. **Target hasn't opted out** (texted STOP or UNSUBSCRIBE)

      **Important SMS Limitations:**
      - Each SMS target counts as a **premium alert**
      - If consent is missing or revoked, **SMS will not be sent**
      - No notification if SMS fails due to consent issues

      > **🛡️ Best Practice**: Always pair SMS alerts with email backup actions. If SMS consent is revoked or the user opts out, you'll still receive email notifications.

      **SMS Consent Warning**: The create alert form shows: *"SMS targets require an account with a verified phone number and consent."*

      #### Action Setup Example
      For critical payment failures, you might set up:
      1. **Email**: `[email protected]` (backup/logging)
      2. **SMS**: `+1234567890` (immediate notification)
      3. **Email**: `[email protected]` (team notification)

      This ensures multiple notification paths and team coverage.

      ## Alert Rule Examples

      ### Security Monitoring
      ```
      Name: "Suspicious Admin Login Activity"
      Event Type: user_login_failed
      Metadata Condition: user.role == "admin"
      Condition: Threshold - 3 events in 5 minutes
      Urgency: Critical
      Actions: Email + SMS to security team
      ```

      ### Error Monitoring
      ```
      Name: "Payment Processing Errors"
      Event Type: payment_failed
      Metadata Condition: error.type LIKE "%timeout%"
      Condition: Threshold - 5 events in 10 minutes
      Urgency: Batch Process
      Actions: Email to development team
      ```

      ### Business Monitoring
      ```
      Name: "High-Value Order Issues"
      Event Type: order_failed
      Metadata Condition: order.amount > 500
      Condition: Any (immediate notification)
      Urgency: Critical
      Actions: Email + SMS to sales team
      ```

      ### System Health
      ```
      Name: "Server Restart Notifications"
      Event Type: server_restart
      Condition: Any
      Urgency: Batch Process
      Actions: Email to operations team
      ```

      ## Best Practices

      ### Event Type Strategy
      - **Be consistent** with event type naming across your application
      - **Use descriptive names**: `payment_failed` not `error`
      - **Group related events**: `user_login`, `user_logout`, `user_register`

      ### Threshold Configuration
      - **Start with higher thresholds** and adjust down if needed
      - **Use time windows** that match your business context
      - **Consider normal usage patterns** when setting counts

      ### Urgency Guidelines
      - **Critical alerts**: Reserved for incidents requiring immediate action
      - **Batch alerts**: Perfect for monitoring and trend detection
      - **Cost management**: Use batch alerts for 80%+ of your rules

      ### Action Management
      - **Always have email backup** for SMS targets
      - **Use team aliases** instead of individual emails when possible
      - **Test your alerts** after creation to verify delivery
      - **Review and update** contact information regularly

      ### Suppression Strategy
      - **Match suppression to urgency**: Critical events need shorter suppression
      - **Consider alert fatigue**: Longer suppression for non-critical issues
      - **Monitor alert frequency** and adjust suppression accordingly

      ## Troubleshooting Common Issues

      ### "SMS Not Delivering"
      1. Check SMS consent in "My User Settings"
      2. Verify phone number is registered and verified
      3. Ensure user hasn't texted STOP or UNSUBSCRIBE
      4. Add email backup action

      ### "Too Many Notifications"
      1. Increase suppression minutes
      2. Switch from "Any" to "Threshold" condition
      3. Refine metadata conditions to be more specific
      4. Consider changing from Critical to Batch urgency

      ### "Missing Expected Alerts"
      1. Verify event type spelling matches your logs exactly
      2. Check metadata field paths (case-sensitive)
      3. Review threshold counts and time windows
      4. Confirm rule is enabled and not suppressed

      ### "Alert Not Triggering"
      1. Test your conditions with recent log data
      2. Verify tenant selection matches your log events
      3. Check if rule has reached suppression limits
      4. Review metadata operators and values

      ## Managing Your Alerts

      - **View all alerts** in the "Alerts" section (both sent and suppressed)
      - **Edit rules** in "Alert Rules" administration
      - **Monitor usage** against your subscription limits
      - **Review alert history** to optimize threshold settings
      - **Update contact preferences** in "My User Settings"

      ## What's Next?

      Now that you understand how to create effective alert rules, you can:

      - **[Explore the dashboard](/guides/dashboard)** to analyze alert patterns and optimize your rules
      - **[Learn about event type strategies](/guides/event-types)** for consistent alerting across your application
      - **Integrate with your application** [javascript & Node.js](/examples/javascript) **[PHP](/examples/php)** **[Python](/examples/python)** **[C#/.NET](/examples/csharp)**

      ---

      **🎉 Ready to create your first alert?** Navigate to Alert Rules and click "+ Rule" to get started. Remember to test your alerts after creation to ensure proper delivery and notification preferences.