Log-Based Testing: Using Structured Logs as Test Oracles
Logs are the oldest form of application observability — and one of the least used in testing. Most teams treat logs as a debugging aid after a failure, not as assertions in a passing test. That's a missed opportunity. When your application emits structured logs (JSON lines with typed fields), you can assert against them just as precisely as you assert against return values. This post shows how.
The Case for Log-Based Testing
There are behaviors that logs capture that function return values don't:
- Security events — "user X attempted to access resource Y without permission" — you want to verify this log fires, even when the HTTP response is just a 403.
- Audit trails — "order created by user X at time T" — the API returns 201, but the audit log entry is the compliance artifact.
- Background jobs — workers don't return HTTP responses; logs are often the only observable output.
- Error recovery — the retry succeeded, so the function returned normally, but you want to verify the retry was logged.
In all these cases, treating the log as a test oracle — the authoritative record of what happened — gives you assertions you cannot make from the return value alone.
Structured Logging Foundations
Log-based testing only works reliably with structured logs. Free-text log lines are fragile to assert against; JSON fields are precise.
# logging_setup.py
import structlog
import logging
def configure_logging():
structlog.configure(
processors=[
structlog.contextvars.merge_contextvars,
structlog.processors.add_log_level,
structlog.processors.TimeStamper(fmt="iso"),
structlog.processors.JSONRenderer()
],
wrapper_class=structlog.make_filtering_bound_logger(logging.DEBUG),
context_class=dict,
logger_factory=structlog.PrintLoggerFactory()
)
log = structlog.get_logger()# order_service.py
def create_order(user_id: str, items: list, request_id: str):
log.info("order.create.started",
user_id=user_id,
item_count=len(items),
request_id=request_id)
try:
order = db.insert_order(user_id, items)
log.info("order.create.succeeded",
user_id=user_id,
order_id=order.id,
request_id=request_id,
total_usd=order.total)
return order
except DatabaseError as e:
log.error("order.create.failed",
user_id=user_id,
request_id=request_id,
error=str(e),
error_code=e.code)
raiseCapturing Logs in Tests
Python: Capturing with a Custom Handler
# conftest.py
import json
import logging
import pytest
class StructuredLogCapture:
def __init__(self):
self.records = []
def clear(self):
self.records = []
def filter(self, event: str = None, **kwargs) -> list:
results = self.records
if event:
results = [r for r in results if r.get("event") == event]
for key, value in kwargs.items():
results = [r for r in results if r.get(key) == value]
return results
def assert_logged(self, event: str, **kwargs):
matches = self.filter(event=event, **kwargs)
assert matches, (
f"Expected log event '{event}' with {kwargs}\n"
f"Captured events: {[r.get('event') for r in self.records]}"
)
return matches[0]
def assert_not_logged(self, event: str, **kwargs):
matches = self.filter(event=event, **kwargs)
assert not matches, f"Expected event '{event}' NOT to be logged, but found: {matches}"
class JSONHandler(logging.Handler):
def __init__(self, capture: StructuredLogCapture):
super().__init__()
self.capture = capture
def emit(self, record: logging.LogRecord):
try:
msg = self.format(record)
parsed = json.loads(msg)
self.capture.records.append(parsed)
except (json.JSONDecodeError, Exception):
pass
@pytest.fixture
def log_capture():
capture = StructuredLogCapture()
handler = JSONHandler(capture)
root_logger = logging.getLogger()
root_logger.addHandler(handler)
yield capture
root_logger.removeHandler(handler)
capture.clear()Node.js: Capturing with Pino
// test-helpers/log-capture.js
const { Writable } = require('stream')
class LogCapture {
constructor() {
this.records = []
this.stream = new Writable({
write: (chunk, encoding, callback) => {
try {
const record = JSON.parse(chunk.toString())
this.records.push(record)
} catch (e) { /* ignore non-JSON */ }
callback()
}
})
}
clear() { this.records = [] }
filter({ msg, level, ...fields } = {}) {
return this.records.filter(r => {
if (msg && r.msg !== msg) return false
if (level && r.level !== level) return false
return Object.entries(fields).every(([k, v]) => r[k] === v)
})
}
assertLogged({ msg, ...fields }) {
const matches = this.filter({ msg, ...fields })
if (!matches.length) {
const events = this.records.map(r => r.msg).join(', ')
throw new Error(`Expected log '${msg}' with ${JSON.stringify(fields)}\nGot: ${events}`)
}
return matches[0]
}
assertNotLogged({ msg, ...fields }) {
const matches = this.filter({ msg, ...fields })
if (matches.length) {
throw new Error(`Expected log '${msg}' NOT to appear, but found: ${JSON.stringify(matches)}`)
}
}
}
module.exports = { LogCapture }// Usage in tests (Jest)
const pino = require('pino')
const { LogCapture } = require('./test-helpers/log-capture')
describe('OrderService', () => {
let capture, logger, service
beforeEach(() => {
capture = new LogCapture()
logger = pino({ level: 'debug' }, capture.stream)
service = new OrderService({ logger })
})
afterEach(() => capture.clear())
test('logs order creation with correct fields', async () => {
await service.createOrder('user-1', [{ sku: 'w001', qty: 2 }], 'req-abc')
capture.assertLogged({
msg: 'order.create.succeeded',
userId: 'user-1',
itemCount: 1
})
})
})Log Assertions in Practice
Asserting Security Events
def test_unauthorized_access_attempt_is_logged(client, log_capture):
response = client.get("/api/admin/users", headers={"Authorization": "Bearer invalid-token"})
assert response.status_code == 401
entry = log_capture.assert_logged(
"auth.access.denied",
endpoint="/api/admin/users",
reason="invalid_token"
)
# Verify sensitive data is NOT logged
assert "token" not in str(entry), "Token value must not appear in logs"
assert entry.get("level") == "warning"
def test_rate_limit_exceeded_logs_client_identifier(client, log_capture):
for _ in range(101):
client.get("/api/products", headers={"X-API-Key": "key-abc"})
entries = log_capture.filter("rate_limit.exceeded", api_key_prefix="key-")
assert len(entries) > 0
assert entries[0]["client_id"] == "key-abc"[:8] # only prefix, not full keyAsserting Retry Behavior
def test_payment_retry_is_logged_on_transient_failure(log_capture, mock_payment_api):
# First call fails, second succeeds
mock_payment_api.side_effect = [TransientError("timeout"), PaymentResult(id="txn-1")]
result = process_payment("order-1", 49.99)
assert result.transaction_id == "txn-1"
# Verify retry was logged
retry_logs = log_capture.filter("payment.retry.attempted")
assert len(retry_logs) == 1
assert retry_logs[0]["attempt"] == 2
assert retry_logs[0]["order_id"] == "order-1"
# Verify eventual success was logged
log_capture.assert_logged("payment.succeeded", order_id="order-1", attempt=2)
def test_payment_exhausted_retries_logs_final_failure(log_capture, mock_payment_api):
mock_payment_api.side_effect = TransientError("timeout")
with pytest.raises(PaymentError):
process_payment("order-2", 99.99)
final_failure = log_capture.assert_logged(
"payment.failed.retries_exhausted",
order_id="order-2"
)
assert final_failure["retry_count"] == 3 # matches configured max retriesAsserting Background Job Logs
def test_email_worker_logs_each_delivery(log_capture, email_queue):
email_queue.enqueue([
{"to": "a@example.com", "subject": "Hello"},
{"to": "b@example.com", "subject": "World"}
])
worker = EmailWorker(log=log_capture)
worker.process_batch()
sent_logs = log_capture.filter("email.sent")
assert len(sent_logs) == 2
recipients = {e["to"] for e in sent_logs}
assert recipients == {"a@example.com", "b@example.com"}
def test_email_worker_logs_bounce_without_raising(log_capture, email_queue, mock_smtp):
mock_smtp.raise_on_send("c@example.com", BounceError("550 no mailbox"))
email_queue.enqueue([{"to": "c@example.com", "subject": "Test"}])
worker = EmailWorker() # should not raise
worker.process_batch()
log_capture.assert_logged("email.bounced",
to="c@example.com",
bounce_code=550)
log_capture.assert_not_logged("email.sent", to="c@example.com")Log-Driven Test Verification for APIs
When an API endpoint has side effects that don't show up in the response body (audit entries, async triggers), logs are the fastest way to verify those side effects fired.
def test_delete_user_emits_gdpr_audit_log(client, log_capture):
client.delete("/api/users/user-42",
headers={"Authorization": "Bearer admin-token"})
audit = log_capture.assert_logged(
"gdpr.user.deleted",
user_id="user-42",
performed_by="admin"
)
# GDPR audit must include deletion timestamp
assert "deleted_at" in audit
assert audit["log_level"] == "critical" # audit logs must be critical level
# PII must not be logged beyond the user ID
assert "email" not in audit
assert "name" not in auditIntegrating Loki in CI
For end-to-end tests where you need to query logs from a running service rather than capturing them in-process, Loki is the right tool. Run it alongside your services in Docker Compose:
# docker-compose.test.yml
services:
loki:
image: grafana/loki:2.9.4
command: -config.file=/etc/loki/local-config.yaml
ports:
- "3100:3100"
promtail:
image: grafana/promtail:2.9.4
volumes:
- /var/log:/var/log
- ./promtail-test.yaml:/etc/promtail/config.yaml
command: -config.file=/etc/promtail/config.yaml
depends_on:
- loki
app:
build: .
logging:
driver: "json-file"
options:
labels: "app,env"
labels:
app: "order-service"
env: "test"# promtail-test.yaml
server:
http_listen_port: 9080
clients:
- url: http://loki:3100/loki/api/v1/push
scrape_configs:
- job_name: docker
docker_sd_configs:
- host: unix:///var/run/docker.sock
refresh_interval: 5s
relabel_configs:
- source_labels: ['__meta_docker_container_label_app']
target_label: appQuery Loki from tests:
# loki_client.py
import requests
import time
import json
class LokiClient:
def __init__(self, base_url: str = "http://localhost:3100"):
self.base_url = base_url
def query(self, logql: str, limit: int = 100, lookback_minutes: int = 5) -> list:
now_ns = int(time.time() * 1e9)
start_ns = now_ns - (lookback_minutes * 60 * int(1e9))
resp = requests.get(
f"{self.base_url}/loki/api/v1/query_range",
params={
"query": logql,
"limit": limit,
"start": start_ns,
"end": now_ns
}
)
resp.raise_for_status()
data = resp.json()
lines = []
for stream in data.get("data", {}).get("result", []):
for ts, line in stream.get("values", []):
try:
lines.append(json.loads(line))
except json.JSONDecodeError:
lines.append({"raw": line})
return lines
def wait_for_log(self, logql: str, timeout: int = 15) -> dict:
deadline = time.time() + timeout
while time.time() < deadline:
results = self.query(logql, lookback_minutes=1)
if results:
return results[-1] # most recent
time.sleep(0.5)
raise AssertionError(f"No log matching '{logql}' found within {timeout}s")# test_with_loki.py
loki = LokiClient()
def test_order_created_log_appears_in_loki(http_client):
http_client.post("/api/orders", json={"item": "widget"})
log_entry = loki.wait_for_log(
'{app="order-service"} |= "order.create.succeeded"'
)
assert log_entry["event"] == "order.create.succeeded"
assert "order_id" in log_entryFluentd for Log Aggregation in Tests
If your pipeline uses Fluentd, configure a file output for test environments so you can assert on aggregated logs:
# fluentd-test.conf
<source>
@type forward
port 24224
</source>
<match app.**>
@type file
path /tmp/test-logs/app
append true
<format>
@type json
</format>
</match># test_with_fluentd.py
import json
import time
def read_fluentd_logs(path: str = "/tmp/test-logs/app") -> list:
records = []
import glob
for log_file in glob.glob(f"{path}*"):
with open(log_file) as f:
for line in f:
line = line.strip()
if line:
# Fluentd file output format: time\ttag\t{json}
parts = line.split("\t", 2)
if len(parts) == 3:
records.append(json.loads(parts[2]))
return recordsNegative Assertions: What Should NOT Be Logged
Negative log assertions are as important as positive ones — verify that sensitive data never leaks into logs:
def test_credit_card_number_never_appears_in_logs(log_capture, client):
client.post("/api/payments", json={
"card_number": "4111111111111111",
"amount": 99.0
})
all_log_content = json.dumps(log_capture.records)
assert "4111111111111111" not in all_log_content
assert "411111111111" not in all_log_content # also check partial numbers
def test_password_not_logged_on_auth_failure(log_capture, client):
client.post("/api/auth/login", json={
"email": "user@example.com",
"password": "s3cr3t-p4ssw0rd"
})
all_log_content = json.dumps(log_capture.records)
assert "s3cr3t-p4ssw0rd" not in all_log_contentConclusion
Structured logs are precise, queryable, and carry context that return values don't. Adding a log capture fixture to your test suite takes 30 minutes; the value is a class of assertions that cover security events, audit requirements, retry behavior, and background jobs — all behaviors that your existing tests likely don't verify. Start by identifying the top five "I only know this worked because I checked the logs" behaviors in your system, and write log assertions for each one.