<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
# API Reference — Implementing API Logging & Monitoring

## Vector — Log Shipping
```bash
# Validate vector config
vector validate /etc/vector/vector.toml

# Run vector with API logs source
vector --config /etc/vector/vector.toml

# Test log pipeline locally
echo '{"method":"GET","path":"/api/users","status_code":200}' | \
  vector --config /etc/vector/vector.toml --stdin
```

## Elasticsearch — Log Queries
```bash
# Search for 401 errors in last hour
curl -s "https://es:9200/api-logs-*/_search" \
  -H "Content-Type: application/json" \
  -d '{"query":{"bool":{"must":[{"term":{"status_code":401}},{"range":{"@timestamp":{"gte":"now-1h"}}}]}}}'

# Get top error endpoints
curl -s "https://es:9200/api-logs-*/_search" \
  -H "Content-Type: application/json" \
  -d '{"size":0,"query":{"range":{"status_code":{"gte":400}}},"aggs":{"paths":{"terms":{"field":"path.keyword","size":10}}}}'
```

## Grafana — Dashboard Provisioning
```bash
# Import dashboard via API
curl -s -X POST "http://grafana:3000/api/dashboards/db" \
  -H "Authorization: Bearer $GRAFANA_TOKEN" \
  -H "Content-Type: application/json" \
  -d @api-monitoring-dashboard.json
```

## ElastAlert — Alert Rules
```bash
# Test alert rule
elastalert-test-rule --config config.yaml rules/brute_force.yaml

# Run ElastAlert
elastalert --config config.yaml --rule rules/brute_force.yaml
```

## jq — Log Analysis
```bash
# Count status codes
cat /var/log/api/access.json | jq -s 'group_by(.status_code) | map({code: .[0].status_code, count: length})'

# Find top IPs with 401s
cat /var/log/api/access.json | jq -s '[.[] | select(.status_code==401)] | group_by(.client_ip) | map({ip: .[0].client_ip, count: length}) | sort_by(-.count)[:10]'
```
