Testing Log Aggregation: Structured Logging, ELK Stack, and Loki

Testing Log Aggregation: Structured Logging, ELK Stack, and Loki

Your logging pipeline is infrastructure. It can fail silently in ways that are extremely hard to debug when you actually need it: during an incident. Logs that never reached Elasticsearch, structured fields that got dropped by a misconfigured Logstash filter, alert rules that query fields that don't exist.

Testing your logging infrastructure is unglamorous work. It's also the work that ensures your observability actually works when you need it.

What to Test in a Log Pipeline

A log pipeline has multiple stages, each of which can fail:

  1. Application — generates log messages with correct format and content
  2. Collection — Fluentd, Fluent Bit, or Filebeat reads and forwards logs
  3. Processing — Logstash or Vector parses, transforms, and enriches logs
  4. Storage — Elasticsearch or Loki stores logs with correct schema
  5. Query — log queries return correct results
  6. Alerting — alert rules fire correctly based on log content

Each stage needs tests.

Testing Application Log Output

The most direct test: verify your application produces correctly structured log messages.

Structured Log Format Validation

import json
import logging
import pytest
from io import StringIO

def test_structured_log_format():
    """Verify application produces valid structured JSON logs"""
    log_output = StringIO()
    
    handler = logging.StreamHandler(log_output)
    handler.setFormatter(JsonFormatter())  # Your custom JSON formatter
    
    logger = logging.getLogger("test")
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    
    # Trigger a log event
    logger.info("User login", extra={
        "user_id": "user-123",
        "action": "login",
        "ip_address": "192.168.1.1"
    })
    
    log_output.seek(0)
    log_entry = json.loads(log_output.read())
    
    # Required fields
    assert "timestamp" in log_entry, "Missing timestamp field"
    assert "level" in log_entry, "Missing level field"
    assert "message" in log_entry, "Missing message field"
    assert "service" in log_entry, "Missing service field"
    assert "trace_id" in log_entry, "Missing trace_id field (required for correlation)"
    
    # Field types
    assert isinstance(log_entry["timestamp"], str), "Timestamp should be ISO string"
    assert log_entry["level"] in ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
    
    # Business fields
    assert log_entry["user_id"] == "user-123"
    assert log_entry["action"] == "login"

def test_error_log_includes_stack_trace():
    """Verify errors include full stack trace in structured format"""
    log_output = StringIO()
    handler = logging.StreamHandler(log_output)
    handler.setFormatter(JsonFormatter())
    logger = logging.getLogger("test_error")
    logger.addHandler(handler)
    
    try:
        raise ValueError("Test error for logging")
    except ValueError:
        logger.exception("Operation failed")
    
    log_output.seek(0)
    log_entry = json.loads(log_output.read())
    
    assert log_entry["level"] == "ERROR"
    assert "exception" in log_entry or "stack_trace" in log_entry
    assert "ValueError" in json.dumps(log_entry)
    assert "Test error for logging" in json.dumps(log_entry)

Log Schema Validation

Define a JSON schema for your log format and validate against it:

import jsonschema

LOG_SCHEMA = {
    "type": "object",
    "required": ["timestamp", "level", "message", "service", "version"],
    "properties": {
        "timestamp": {
            "type": "string",
            "pattern": r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}"
        },
        "level": {
            "type": "string",
            "enum": ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
        },
        "message": {"type": "string", "minLength": 1},
        "service": {"type": "string"},
        "version": {"type": "string"},
        "trace_id": {"type": "string"},
        "span_id": {"type": "string"},
    },
    "additionalProperties": True  # Allow extension fields
}

@pytest.mark.parametrize("log_event", load_sample_log_events())
def test_log_schema_compliance(log_event):
    """All log events must comply with the schema"""
    try:
        jsonschema.validate(instance=log_event, schema=LOG_SCHEMA)
    except jsonschema.ValidationError as e:
        pytest.fail(f"Log event failed schema validation: {e.message}\nEvent: {log_event}")

Testing the Collection Layer

Verify that log collection agents (Filebeat, Fluent Bit, Fluentd) are correctly reading and forwarding logs.

Filebeat Configuration Testing

# filebeat-test.yml — minimal config for testing
filebeat.inputs:
  - type: log
    paths:
      - /tmp/test-logs/*.log
    json.keys_under_root: true
    json.add_error_key: true

output.file:
  path: /tmp/filebeat-output
  filename: output.json
import subprocess
import time
import json

def test_filebeat_forwards_json_logs(tmp_path):
    """Verify Filebeat correctly reads and forwards JSON log files"""
    log_file = tmp_path / "app.log"
    output_dir = tmp_path / "output"
    output_dir.mkdir()
    
    # Write test log entries
    test_entries = [
        {"timestamp": "2026-05-30T10:00:00Z", "level": "INFO", "message": "Test 1"},
        {"timestamp": "2026-05-30T10:00:01Z", "level": "ERROR", "message": "Test 2"},
    ]
    
    with open(log_file, "w") as f:
        for entry in test_entries:
            f.write(json.dumps(entry) + "\n")
    
    # Run Filebeat
    proc = subprocess.Popen([
        "filebeat", "-e", "-c", "filebeat-test.yml",
        "-E", f"filebeat.inputs.0.paths=[{log_file}]",
        "-E", f"output.file.path={output_dir}"
    ])
    
    time.sleep(5)
    proc.terminate()
    
    # Verify output
    output_files = list(output_dir.glob("*.json"))
    assert output_files, "Filebeat produced no output"
    
    forwarded = []
    for f in output_files:
        with open(f) as fp:
            for line in fp:
                if line.strip():
                    forwarded.append(json.loads(line))
    
    assert len(forwarded) >= 2, f"Expected 2 forwarded events, got {len(forwarded)}"
    messages = [e.get("message") for e in forwarded]
    assert "Test 1" in messages
    assert "Test 2" in messages

Testing Logstash/Vector Processing

Processing pipelines transform log fields. Test that transformations are correct.

Logstash Filter Unit Testing

Use the logstash-filter-tester or the Logstash rspec framework:

# spec/filters/parse_http_access_log_spec.rb
require_relative '../spec_helper'

describe "HTTP access log parsing" do
  config <<-CONFIG
    filter {
      grok {
        match => {
          "message" => '%{IP:client_ip} - %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:method} %{URIPATH:path} HTTP/%{NUMBER:http_version}" %{NUMBER:status_code:int} %{NUMBER:response_bytes:int}'
        }
      }
      date {
        match => ["timestamp", "dd/MMM/yyyy:HH:mm:ss Z"]
        target => "@timestamp"
      }
      mutate {
        convert => { "status_code" => "integer" }
        add_field => { "status_class" => "%{status_code}" }
      }
    }
  CONFIG

  sample '192.168.1.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326' do
    insist { subject.get("client_ip") } == "192.168.1.1"
    insist { subject.get("method") } == "GET"
    insist { subject.get("status_code") } == 200
    insist { subject.get("response_bytes") } == 2326
    reject { subject.get("tags") }.include?("_grokparsefailure")
  end

  sample 'invalid log line without proper format' do
    insist { subject.get("tags") }.include?("_grokparsefailure")
  end
end

Vector Transform Testing

# Test Vector VRL (Vector Remap Language) transforms
cat test-input.json | vector test --test-file vector-tests.yaml
# vector-tests.yaml
tests:
  - name: "Parse and enrich HTTP logs"
    inputs:
      - insert_at: parse_http
        value:
          message: '{"method":"GET","path":"/api/users","status":200,"duration_ms":45}'
    outputs:
      - extract_from: enrich_logs
        conditions:
          - type: vrl
            source: |
              assert_eq!(.method, "GET")
              assert_eq!(.status, 200)
              assert!(.duration_ms < 1000, "Unexpected high latency in test data")
              assert!(exists(.service_name), "service_name must be added by enrichment")
              assert!(exists(.environment), "environment must be added by enrichment")

Testing Elasticsearch/Loki Storage

Verify that logs are stored with the correct schema and are queryable.

Elasticsearch Index Mapping Tests

from elasticsearch import Elasticsearch
import pytest

es = Elasticsearch("http://localhost:9200")

def test_index_mapping_matches_schema():
    """Verify Elasticsearch index has correct field mappings"""
    mapping = es.indices.get_mapping(index="app-logs-*")
    
    # Get mapping for a specific index
    index_name = sorted(mapping.keys())[0]
    props = mapping[index_name]["mappings"]["properties"]
    
    required_fields = {
        "timestamp": "date",
        "level": "keyword",
        "message": "text",
        "service": "keyword",
        "trace_id": "keyword",
        "span_id": "keyword",
    }
    
    for field_name, expected_type in required_fields.items():
        assert field_name in props, f"Missing field mapping: {field_name}"
        actual_type = props[field_name].get("type")
        assert actual_type == expected_type, \
            f"Field '{field_name}': expected type '{expected_type}', got '{actual_type}'"

def test_logs_are_queryable():
    """Verify stored logs can be retrieved with expected queries"""
    # Search for error logs in the last hour
    result = es.search(
        index="app-logs-*",
        body={
            "query": {
                "bool": {
                    "filter": [
                        {"term": {"level": "ERROR"}},
                        {"range": {"timestamp": {"gte": "now-1h"}}}
                    ]
                }
            },
            "size": 10
        }
    )
    
    # Verify the query works (not necessarily that errors exist)
    assert result["_shards"]["failed"] == 0, "Query had shard failures"
    assert "hits" in result

def test_trace_id_lookup():
    """Verify logs can be correlated by trace ID"""
    test_trace_id = "test-trace-abc123"
    
    result = es.search(
        index="app-logs-*",
        body={
            "query": {"term": {"trace_id": test_trace_id}},
            "sort": [{"timestamp": "asc"}]
        }
    )
    
    # If trace ID exists, verify all returned logs have the correct trace_id
    for hit in result["hits"]["hits"]:
        assert hit["_source"]["trace_id"] == test_trace_id

Loki Query Testing

import requests

LOKI_URL = "http://localhost:3100"

def loki_query(logql: str, limit: int = 100) -> list:
    response = requests.get(
        f"{LOKI_URL}/loki/api/v1/query_range",
        params={
            "query": logql,
            "limit": limit,
            "start": "now-1h",
            "end": "now"
        }
    )
    response.raise_for_status()
    return response.json()["data"]["result"]

def test_loki_error_query():
    """Verify error logs are queryable in Loki"""
    results = loki_query('{app="my-service"} |= "ERROR"')
    
    # Query should execute without error
    # (we don't require errors to exist, just that the query works)
    assert isinstance(results, list)

def test_loki_structured_metadata():
    """Verify structured log fields are queryable"""
    results = loki_query(
        '{app="my-service"} | json | level="ERROR" | duration_ms > 1000'
    )
    
    # All returned results should have duration_ms > 1000
    for stream in results:
        for entry in stream["values"]:
            timestamp, log_line = entry
            parsed = json.loads(log_line)
            assert parsed.get("level") == "ERROR"
            assert parsed.get("duration_ms", 0) > 1000

Testing Log-Based Alerting

Alert rules that query logs need to be tested. A broken alert rule silently fails to fire when it should.

Prometheus Alertmanager with Loki

def test_error_rate_alert_fires():
    """Verify that high error rate triggers alert"""
    # Inject test error logs
    for _ in range(100):
        inject_log_event({
            "level": "ERROR",
            "service": "test-service",
            "message": "Test error for alerting validation"
        })
    
    time.sleep(60)  # Wait for Loki rule evaluation interval
    
    # Check if alert fired
    response = requests.get("http://localhost:9093/api/v2/alerts")
    alerts = response.json()
    
    error_rate_alerts = [
        a for a in alerts 
        if a["labels"].get("alertname") == "HighErrorRate"
        and a["labels"].get("service") == "test-service"
    ]
    
    assert error_rate_alerts, "HighErrorRate alert did not fire after injecting errors"
    assert error_rate_alerts[0]["status"]["state"] == "active"

End-to-End Pipeline Testing

Test the complete path: application log → collection → storage → queryable.

import uuid
import time

def test_end_to_end_log_pipeline():
    """Verify a log event travels from application to storage and is queryable"""
    
    # Generate a unique trace ID to track this specific log event
    trace_id = str(uuid.uuid4())
    test_message = f"E2E pipeline test {trace_id}"
    
    # Step 1: Generate the log event
    logger.info(test_message, extra={"trace_id": trace_id, "test_marker": "e2e"})
    
    # Step 2: Wait for pipeline processing (collection + storage latency)
    max_wait_seconds = 60
    poll_interval = 5
    
    for attempt in range(max_wait_seconds // poll_interval):
        time.sleep(poll_interval)
        
        # Step 3: Query for the log event
        results = loki_query(f'{{app="my-service"}} |= "{trace_id}"')
        
        if results:
            # Found it — verify content
            all_entries = [
                json.loads(entry[1]) 
                for stream in results 
                for entry in stream["values"]
            ]
            
            matching = [e for e in all_entries if trace_id in json.dumps(e)]
            assert matching, f"Found results but trace_id not in content"
            assert matching[0]["message"] == test_message
            return  # Test passed
    
    pytest.fail(
        f"Log event with trace_id={trace_id} not found in Loki after {max_wait_seconds}s"
    )

Testing Log Pipeline Resilience

What happens when part of the pipeline goes down?

def test_log_pipeline_buffering_during_storage_outage():
    """Verify logs are buffered during storage outage and delivered after recovery"""
    
    # Generate baseline log count
    baseline_count = count_logs_in_loki(last_minutes=5)
    
    # Stop Elasticsearch/Loki
    subprocess.run(["docker", "stop", "elasticsearch"])
    
    # Generate logs during outage
    for i in range(50):
        logger.info(f"Log during outage {i}", extra={"outage_test": True})
    
    time.sleep(10)
    
    # Restart storage
    subprocess.run(["docker", "start", "elasticsearch"])
    
    # Wait for buffer to drain
    time.sleep(30)
    
    # Verify buffered logs were delivered
    new_count = count_logs_in_loki(last_minutes=5)
    delivered = new_count - baseline_count
    
    assert delivered >= 45, \
        f"Only {delivered} of 50 buffered logs delivered after outage recovery"

HelpMeTest monitors your services with continuous health checks, giving you the uptime and response time data that complements your log aggregation pipeline — a fast signal when something is wrong, before you need to dig into the logs. Start free.

Read more

Start now free