diff --git a/.env.example b/.env.example index 4874fde..41547bd 100644 --- a/.env.example +++ b/.env.example @@ -38,5 +38,13 @@ ER_COLLECTOR_PROJECT_ALPHA_TOKEN=er_tst_a_secret_one # MAX_BACKOFF_EXPONENT=8 # COLLECTOR_DEFAULT_INGEST_TOKEN= +# --- Log level (ingest-api, collector-worker, api) --- +# Controls verbosity. Values: trace | debug | info | warn | error | fatal +# LOG_LEVEL=info + +# --- Observability: Loki (profile: observability) --- +# Host port mapped to Loki HTTP API +# ER_PUBLISH_LOKI_PORT=3100 + # Node apps (ingest-api, collector-worker, api/) expect: # DATABASE_URL=mysql://USER:PASSWORD@HOST:PORT/DATABASE diff --git a/deploy/grafana/loki-logs-dashboard.json b/deploy/grafana/loki-logs-dashboard.json new file mode 100644 index 0000000..34585fc --- /dev/null +++ b/deploy/grafana/loki-logs-dashboard.json @@ -0,0 +1,567 @@ +{ + "__inputs": [ + { + "name": "DS_LOKI", + "label": "Loki", + "description": "Loki log aggregation datasource", + "type": "datasource", + "pluginId": "loki", + "pluginName": "Loki" + } + ], + "__requires": [ + { + "type": "grafana", + "id": "grafana", + "name": "Grafana", + "version": "10.0.0" + }, + { + "type": "datasource", + "id": "loki", + "name": "Loki", + "version": "1.0.0" + }, + { + "type": "panel", + "id": "logs", + "name": "Logs", + "version": "" + }, + { + "type": "panel", + "id": "timeseries", + "name": "Time series", + "version": "" + }, + { + "type": "panel", + "id": "stat", + "name": "Stat", + "version": "" + }, + { + "type": "panel", + "id": "piechart", + "name": "Pie chart", + "version": "" + } + ], + "annotations": { + "list": [] + }, + "description": "Centralised log view for all errors.bitreport.pt services via Loki. Docs: docs/OBSERVABILITY_LOKI.md", + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 1, + "id": null, + "links": [ + { + "icon": "external link", + "title": "Error Monitoring SLO", + "tooltip": "Prometheus operational dashboard", + "type": "link", + "url": "/d/er-ops-slo" + } + ], + "panels": [ + { + "collapsed": false, + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 }, + "id": 100, + "title": "Overview", + "type": "row" + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "thresholds" }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "green", "value": null }, + { "color": "yellow", "value": 1 }, + { "color": "red", "value": 10 } + ] + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { "h": 4, "w": 4, "x": 0, "y": 1 }, + "id": 1, + "options": { + "colorMode": "background", + "graphMode": "none", + "justifyMode": "center", + "orientation": "auto", + "reduceOptions": { "calcs": ["sum"], "fields": "", "values": false }, + "textMode": "auto" + }, + "title": "Errors (window)", + "type": "stat", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "sum(count_over_time({app=\"errors-hub\", level=\"error\"}[$__range]))", + "legendFormat": "errors", + "refId": "A" + } + ] + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "thresholds" }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "green", "value": null }, + { "color": "red", "value": 1 } + ] + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { "h": 4, "w": 4, "x": 4, "y": 1 }, + "id": 2, + "options": { + "colorMode": "background", + "graphMode": "none", + "justifyMode": "center", + "orientation": "auto", + "reduceOptions": { "calcs": ["sum"], "fields": "", "values": false }, + "textMode": "auto" + }, + "title": "Fatals (window)", + "type": "stat", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "sum(count_over_time({app=\"errors-hub\", level=\"fatal\"}[$__range]))", + "legendFormat": "fatals", + "refId": "A" + } + ] + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "thresholds" }, + "mappings": [], + "thresholds": { + "mode": "absolute", + "steps": [ + { "color": "green", "value": null }, + { "color": "yellow", "value": 50 }, + { "color": "red", "value": 200 } + ] + }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { "h": 4, "w": 4, "x": 8, "y": 1 }, + "id": 3, + "options": { + "colorMode": "value", + "graphMode": "none", + "justifyMode": "center", + "orientation": "auto", + "reduceOptions": { "calcs": ["sum"], "fields": "", "values": false }, + "textMode": "auto" + }, + "title": "Warnings (window)", + "type": "stat", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "sum(count_over_time({app=\"errors-hub\", level=\"warn\"}[$__range]))", + "legendFormat": "warnings", + "refId": "A" + } + ] + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "palette-classic" }, + "custom": { + "hideFrom": { "legend": false, "tooltip": false, "viz": false } + } + }, + "overrides": [] + }, + "gridPos": { "h": 4, "w": 12, "x": 12, "y": 1 }, + "id": 4, + "options": { + "displayLabels": ["name", "percent"], + "legend": { "displayMode": "table", "placement": "right", "values": ["value"] }, + "pieType": "donut", + "tooltip": { "mode": "single", "sort": "none" } + }, + "title": "Log volume by level (window)", + "type": "piechart", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "sum by (level) (count_over_time({app=\"errors-hub\"}[$__range]))", + "legendFormat": "{{level}}", + "refId": "A" + } + ] + }, + { + "collapsed": false, + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 5 }, + "id": 101, + "title": "Log Rate", + "type": "row" + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "palette-classic" }, + "custom": { + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "lines/s", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "bars", + "fillOpacity": 70, + "gradientMode": "none", + "hideFrom": { "legend": false, "tooltip": false, "viz": false }, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { "type": "linear" }, + "showPoints": "never", + "spanNulls": false, + "stacking": { "group": "A", "mode": "normal" }, + "thresholdsStyle": { "mode": "off" } + }, + "mappings": [], + "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] }, + "unit": "short" + }, + "overrides": [ + { "matcher": { "id": "byName", "options": "error" }, "properties": [{ "id": "color", "value": { "fixedColor": "red", "mode": "fixed" } }] }, + { "matcher": { "id": "byName", "options": "fatal" }, "properties": [{ "id": "color", "value": { "fixedColor": "dark-red", "mode": "fixed" } }] }, + { "matcher": { "id": "byName", "options": "warn" }, "properties": [{ "id": "color", "value": { "fixedColor": "orange", "mode": "fixed" } }] }, + { "matcher": { "id": "byName", "options": "info" }, "properties": [{ "id": "color", "value": { "fixedColor": "blue", "mode": "fixed" } }] } + ] + }, + "gridPos": { "h": 8, "w": 12, "x": 0, "y": 6 }, + "id": 10, + "options": { + "legend": { "calcs": ["sum"], "displayMode": "table", "placement": "bottom", "showLegend": true }, + "tooltip": { "mode": "multi", "sort": "desc" } + }, + "title": "Log rate by level", + "type": "timeseries", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "sum by (level) (rate({app=\"errors-hub\"}[2m]))", + "legendFormat": "{{level}}", + "refId": "A" + } + ] + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "palette-classic" }, + "custom": { + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "lines/s", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "bars", + "fillOpacity": 70, + "gradientMode": "none", + "hideFrom": { "legend": false, "tooltip": false, "viz": false }, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { "type": "linear" }, + "showPoints": "never", + "spanNulls": false, + "stacking": { "group": "A", "mode": "normal" }, + "thresholdsStyle": { "mode": "off" } + }, + "mappings": [], + "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }] }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { "h": 8, "w": 12, "x": 12, "y": 6 }, + "id": 11, + "options": { + "legend": { "calcs": ["sum"], "displayMode": "table", "placement": "bottom", "showLegend": true }, + "tooltip": { "mode": "multi", "sort": "desc" } + }, + "title": "Log rate by service", + "type": "timeseries", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "sum by (service) (rate({app=\"errors-hub\"}[2m]))", + "legendFormat": "{{service}}", + "refId": "A" + } + ] + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "fieldConfig": { + "defaults": { + "color": { "mode": "palette-classic" }, + "custom": { + "axisCenteredZero": false, + "axisColorMode": "text", + "axisLabel": "errors/s", + "axisPlacement": "auto", + "barAlignment": 0, + "drawStyle": "bars", + "fillOpacity": 70, + "gradientMode": "none", + "hideFrom": { "legend": false, "tooltip": false, "viz": false }, + "lineInterpolation": "linear", + "lineWidth": 1, + "pointSize": 5, + "scaleDistribution": { "type": "linear" }, + "showPoints": "never", + "spanNulls": false, + "stacking": { "group": "A", "mode": "normal" }, + "thresholdsStyle": { "mode": "off" } + }, + "mappings": [], + "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }, { "color": "red", "value": 0.01 }] }, + "unit": "short" + }, + "overrides": [] + }, + "gridPos": { "h": 8, "w": 24, "x": 0, "y": 14 }, + "id": 12, + "options": { + "legend": { "calcs": ["max", "sum"], "displayMode": "table", "placement": "bottom", "showLegend": true }, + "tooltip": { "mode": "multi", "sort": "desc" } + }, + "title": "Error + Fatal rate by service", + "type": "timeseries", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "sum by (service) (rate({app=\"errors-hub\", level=~\"error|fatal\"}[2m]))", + "legendFormat": "{{service}}", + "refId": "A" + } + ] + }, + { + "collapsed": false, + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 22 }, + "id": 102, + "title": "Error & Fatal Logs", + "type": "row" + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "gridPos": { "h": 14, "w": 24, "x": 0, "y": 23 }, + "id": 20, + "options": { + "dedupStrategy": "none", + "enableLogDetails": true, + "prettifyLogMessage": false, + "showCommonLabels": false, + "showLabels": false, + "showTime": true, + "sortOrder": "Descending", + "wrapLogMessage": true + }, + "title": "Errors & Fatals — all services", + "type": "logs", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "{app=\"errors-hub\", level=~\"error|fatal\"} | json", + "legendFormat": "", + "refId": "A" + } + ] + }, + { + "collapsed": false, + "gridPos": { "h": 1, "w": 24, "x": 0, "y": 37 }, + "id": 103, + "title": "Service Logs", + "type": "row" + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "gridPos": { "h": 10, "w": 12, "x": 0, "y": 38 }, + "id": 30, + "options": { + "dedupStrategy": "none", + "enableLogDetails": true, + "prettifyLogMessage": false, + "showCommonLabels": false, + "showLabels": false, + "showTime": true, + "sortOrder": "Descending", + "wrapLogMessage": false + }, + "title": "ingest-api logs", + "type": "logs", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "{app=\"errors-hub\", service=\"ingest-api\"} | json | line_format \"[{{.level}}] {{.msg}}{{if .err}} err={{.err}}{{end}}\"", + "legendFormat": "", + "refId": "A" + } + ] + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "gridPos": { "h": 10, "w": 12, "x": 12, "y": 38 }, + "id": 31, + "options": { + "dedupStrategy": "none", + "enableLogDetails": true, + "prettifyLogMessage": false, + "showCommonLabels": false, + "showLabels": false, + "showTime": true, + "sortOrder": "Descending", + "wrapLogMessage": false + }, + "title": "collector-worker logs", + "type": "logs", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "{app=\"errors-hub\", service=\"collector-worker\"} | json | line_format \"[{{.level}}] {{.msg}}{{if .err}} err={{.err}}{{end}}\"", + "legendFormat": "", + "refId": "A" + } + ] + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "gridPos": { "h": 10, "w": 12, "x": 0, "y": 48 }, + "id": 32, + "options": { + "dedupStrategy": "none", + "enableLogDetails": true, + "prettifyLogMessage": false, + "showCommonLabels": false, + "showLabels": false, + "showTime": true, + "sortOrder": "Descending", + "wrapLogMessage": false + }, + "title": "admin-ui logs", + "type": "logs", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "{app=\"errors-hub\", service=\"admin-ui\"} | json", + "legendFormat": "", + "refId": "A" + } + ] + }, + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "gridPos": { "h": 10, "w": 12, "x": 12, "y": 48 }, + "id": 33, + "options": { + "dedupStrategy": "none", + "enableLogDetails": true, + "prettifyLogMessage": false, + "showCommonLabels": false, + "showLabels": false, + "showTime": true, + "sortOrder": "Descending", + "wrapLogMessage": false + }, + "title": "api logs", + "type": "logs", + "targets": [ + { + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "expr": "{app=\"errors-hub\", service=\"api\"} | json | line_format \"[{{.level}}] {{.msg}}{{if .err}} err={{.err}}{{end}}\"", + "legendFormat": "", + "refId": "A" + } + ] + } + ], + "refresh": "30s", + "schemaVersion": 38, + "tags": ["bitreport", "loki", "logs"], + "templating": { + "list": [ + { + "current": {}, + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "definition": "label_values({app=\"errors-hub\"}, service)", + "hide": 0, + "includeAll": true, + "multi": true, + "name": "service", + "options": [], + "query": { + "label": "service", + "refId": "LokiVariableQueryEditor-VariableQuery", + "stream": "{app=\"errors-hub\"}", + "type": 1 + }, + "refresh": 2, + "sort": 1, + "type": "query", + "label": "Service" + }, + { + "current": { "selected": false, "text": "All", "value": "$__all" }, + "datasource": { "type": "loki", "uid": "${DS_LOKI}" }, + "definition": "label_values({app=\"errors-hub\"}, level)", + "hide": 0, + "includeAll": true, + "multi": true, + "name": "level", + "options": [], + "query": { + "label": "level", + "refId": "LokiVariableQueryEditor-VariableQuery", + "stream": "{app=\"errors-hub\"}", + "type": 1 + }, + "refresh": 2, + "sort": 1, + "type": "query", + "label": "Level" + } + ] + }, + "time": { "from": "now-1h", "to": "now" }, + "timepicker": {}, + "timezone": "browser", + "title": "BitReport — Loki Logs", + "uid": "er-loki-logs", + "version": 1 +} diff --git a/deploy/loki/loki.yaml b/deploy/loki/loki.yaml new file mode 100644 index 0000000..edd568b --- /dev/null +++ b/deploy/loki/loki.yaml @@ -0,0 +1,56 @@ +# Loki configuration for errors.bitreport.pt log aggregation. +# Docs: docs/OBSERVABILITY_LOKI.md + +auth_enabled: false + +server: + http_listen_port: 3100 + grpc_listen_port: 9096 + log_level: warn + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +query_range: + results_cache: + cache: + embedded_cache: + enabled: true + max_size_mb: 100 + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +ruler: + alertmanager_url: http://localhost:9093 + +limits_config: + retention_period: 30d + ingestion_rate_mb: 4 + ingestion_burst_size_mb: 8 + max_cache_freshness_per_query: 10m + reject_old_samples: true + reject_old_samples_max_age: 168h + +compactor: + working_directory: /loki/compactor + retention_enabled: true + retention_delete_delay: 2h + retention_delete_worker_count: 150 + delete_request_store: filesystem diff --git a/deploy/loki/promtail.yaml b/deploy/loki/promtail.yaml new file mode 100644 index 0000000..e98a7b4 --- /dev/null +++ b/deploy/loki/promtail.yaml @@ -0,0 +1,82 @@ +# Promtail configuration for errors.bitreport.pt log shipping. +# Discovers Docker containers by compose service name, parses structured JSON logs, +# and ships to the Loki instance in the same Docker network. +# Docs: docs/OBSERVABILITY_LOKI.md + +server: + http_listen_port: 9080 + grpc_listen_port: 0 + log_level: warn + +positions: + filename: /run/promtail/positions.yaml + +clients: + - url: http://loki:3100/loki/api/v1/push + backoff_config: + min_period: 500ms + max_period: 5m + max_retries: 10 + +scrape_configs: + # --- errors-hub services (Docker Compose auto-discovery) --- + - job_name: errors-hub-docker + docker_sd_configs: + - host: unix:///var/run/docker.sock + refresh_interval: 10s + filters: + # Only scrape containers that belong to this compose project. + - name: label + values: ["com.docker.compose.project=errors-bitreport-pt"] + + relabel_configs: + # Map compose service name → `service` label + - source_labels: [__meta_docker_container_label_com_docker_compose_service] + target_label: service + # Compose project → `compose_project` + - source_labels: [__meta_docker_container_label_com_docker_compose_project] + target_label: compose_project + # Container name for uniqueness + - source_labels: [__meta_docker_container_name] + regex: "/(.*)" + target_label: container + # Static labels for every log line from this hub + - replacement: errors-hub + target_label: app + - replacement: production + target_label: env + + pipeline_stages: + # ── Attempt JSON parse ────────────────────────────────────────────── + - json: + expressions: + # Pino uses a numeric `level` (30=info, 40=warn, 50=error) + # Collector-worker uses a string `level` ("info"/"warn"/"error") + pino_level: level + log_msg: msg + log_err: err + log_pid: pid + + # ── Normalize Pino numeric levels to strings ──────────────────────── + # Pino: 10=trace 20=debug 30=info 40=warn 50=error 60=fatal + - template: + source: pino_level + template: | + {{ if eq .Value "10" }}trace + {{- else if eq .Value "20" }}debug + {{- else if eq .Value "30" }}info + {{- else if eq .Value "40" }}warn + {{- else if eq .Value "50" }}error + {{- else if eq .Value "60" }}fatal + {{- else }}{{ .Value }} + {{- end }} + + # Promote the normalized level to a Loki label (low-cardinality) + - labels: + level: pino_level + + # ── Drop noisy debug/trace in production ──────────────────────────── + - match: + selector: '{level=~"trace|debug"}' + action: drop + drop_counter_reason: below_min_level diff --git a/docker-compose.yml b/docker-compose.yml index 9040ebc..c8aa247 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -69,6 +69,7 @@ services: NODE_ENV: production INGEST_RATE_LIMIT_MAX: ${INGEST_RATE_LIMIT_MAX:-300} INGEST_RATE_LIMIT_WINDOW_MS: ${INGEST_RATE_LIMIT_WINDOW_MS:-60000} + LOG_LEVEL: ${LOG_LEVEL:-info} ports: - "${ER_PUBLISH_INGEST_PORT:-3041}:3041" healthcheck: @@ -105,6 +106,7 @@ services: INGEST_PUSH_RETRY_MAX_JITTER_MS: ${INGEST_PUSH_RETRY_MAX_JITTER_MS:-250} MAX_BACKOFF_EXPONENT: ${MAX_BACKOFF_EXPONENT:-8} NODE_ENV: production + LOG_LEVEL: ${LOG_LEVEL:-info} ER_COLLECTOR_PROJECT_ALPHA_TOKEN: ${ER_COLLECTOR_PROJECT_ALPHA_TOKEN:-er_tst_a_secret_one} COLLECTOR_DEFAULT_INGEST_TOKEN: ${COLLECTOR_DEFAULT_INGEST_TOKEN:-} restart: unless-stopped @@ -135,3 +137,39 @@ services: timeout: 5s retries: 6 start_period: 45s + + # ── Loki log aggregation (profile: observability) ────────────────────── + # Start with: docker compose --profile observability up + # Docs: docs/OBSERVABILITY_LOKI.md + loki: + image: grafana/loki:3.4.3 + profiles: [observability] + command: -config.file=/etc/loki/loki.yaml + volumes: + - ./deploy/loki/loki.yaml:/etc/loki/loki.yaml:ro + - loki-data:/loki + ports: + - "${ER_PUBLISH_LOKI_PORT:-3100}:3100" + healthcheck: + test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:3100/ready || exit 1"] + interval: 10s + timeout: 5s + retries: 12 + start_period: 30s + + promtail: + image: grafana/promtail:3.4.3 + profiles: [observability] + command: -config.file=/etc/promtail/promtail.yaml + depends_on: + loki: + condition: service_healthy + volumes: + - ./deploy/loki/promtail.yaml:/etc/promtail/promtail.yaml:ro + - /var/run/docker.sock:/var/run/docker.sock:ro + - /var/lib/docker/containers:/var/lib/docker/containers:ro + - promtail-positions:/run/promtail + +volumes: + loki-data: + promtail-positions: diff --git a/docs/OBSERVABILITY_LOKI.md b/docs/OBSERVABILITY_LOKI.md new file mode 100644 index 0000000..d41b301 --- /dev/null +++ b/docs/OBSERVABILITY_LOKI.md @@ -0,0 +1,176 @@ +# Loki Log Aggregation — errors.bitreport.pt + +Centralised log aggregation for all errors.bitreport.pt services using Grafana Loki + Promtail. + +## Architecture + +``` +ingest-api ──┐ +collector-worker ─┤ stdout/stderr ┌──────────────┐ HTTP push ┌──────┐ +admin-ui ──┤ ──────────────────▶│ Promtail │──────────────▶│ Loki │ +api ──┤ (Docker socket) │ (Docker SD) │ └──────┘ +mariadb ──┘ └──────────────┘ │ + ▼ + Grafana (LogQL) +``` + +Promtail discovers containers via the Docker socket by matching the `errors-bitreport-pt` compose project label. All services emit structured JSON logs (Pino format); Promtail parses them and normalises Pino numeric levels to human-readable strings before shipping. + +## Starting the observability stack + +```bash +# Start core services + Loki + Promtail +docker compose --profile observability up -d + +# Core services only (no log aggregation) +docker compose up -d +``` + +Loki listens on port `3100` (configurable via `ER_PUBLISH_LOKI_PORT` in `.env`). + +## Loki labels + +Every log line carries these labels: + +| Label | Source | Example values | +|---|---|---| +| `service` | compose service name | `ingest-api`, `collector-worker`, `admin-ui` | +| `compose_project` | Docker label | `errors-bitreport-pt` | +| `container` | Docker container name | `/errors-bitreport-pt-ingest-api-1` | +| `app` | static | `errors-hub` | +| `env` | static | `production` | +| `level` | normalised from Pino JSON `level` field | `info`, `warn`, `error`, `fatal` | + +`trace` and `debug` lines are **dropped** by Promtail in production. + +## Key LogQL queries + +### Error logs across all services (last 1 h) +```logql +{app="errors-hub", level="error"} | json +``` + +### Logs for a specific service +```logql +{app="errors-hub", service="ingest-api"} | json +``` + +### Error rate per service (rate over 5 m) +```logql +sum by (service) (rate({app="errors-hub", level="error"}[5m])) +``` + +### Fatal logs (immediate on-call signal) +```logql +{app="errors-hub", level="fatal"} | json +``` + +### Ingest API request logs — errors only +```logql +{service="ingest-api", level="error"} | json | line_format "{{.msg}} err={{.err}}" +``` + +### Collector-worker retry / backoff events +```logql +{service="collector-worker"} |= "retry" | json +``` + +### All logs containing a specific error string +```logql +{app="errors-hub"} |= "ECONNREFUSED" +``` + +### Log volume by service over time (panel query) +```logql +sum by (service) (count_over_time({app="errors-hub"}[1m])) +``` + +## Grafana integration + +The Loki datasource must be added to Grafana with URL `http://loki:3100` (or the host-mapped port if Grafana runs outside the compose network). + +The pre-built log visualisation dashboard is at `deploy/grafana/loki-logs-dashboard.json`. Import it via **Dashboards → Import → Upload JSON**. + +The dashboard requires a Loki datasource named `Loki` (or update the `datasource` field in the JSON to match your instance name). + +## Troubleshooting + +### Promtail not shipping logs + +1. Check Promtail is running and healthy: + ```bash + docker compose --profile observability ps promtail + curl http://localhost:9080/ready + ``` + +2. Inspect Promtail targets (shows which containers are being scraped): + ```bash + curl http://localhost:9080/targets + ``` + +3. Check Promtail logs for errors: + ```bash + docker compose --profile observability logs promtail --tail=50 + ``` + +4. Verify the Docker socket is accessible: + ```bash + docker compose --profile observability exec promtail ls -la /var/run/docker.sock + ``` + +### Loki not receiving data + +1. Check Loki readiness: + ```bash + curl http://localhost:3100/ready + # expected: "ready" + ``` + +2. Inspect Loki ingestion metrics: + ```bash + curl -s http://localhost:3100/metrics | grep loki_distributor_lines + ``` + +3. Check for rejected samples (old timestamps): + ```bash + curl -s http://localhost:3100/metrics | grep loki_discarded_samples + ``` + + If services were offline for > 168 h (the `reject_old_samples_max_age`), logs from the gap period will be rejected. Adjust `reject_old_samples_max_age` in `deploy/loki/loki.yaml` if needed. + +### Logs visible in Loki but not in Grafana + +1. Confirm the Grafana datasource URL points to Loki (`http://loki:3100` inside Docker, or `http://localhost:3100` / configured `ER_PUBLISH_LOKI_PORT` from the host). +2. Verify the time range in the Grafana explore panel covers when services were running. +3. Run a raw label query to confirm data exists: + ```bash + curl 'http://localhost:3100/loki/api/v1/labels' + curl 'http://localhost:3100/loki/api/v1/query?query=\{app="errors-hub"\}&limit=5' + ``` + +### JSON not being parsed (raw log lines in Grafana) + +Promtail only runs the JSON pipeline stage; if a service emits plain-text lines (e.g. MariaDB), the `json` stage is silently skipped and the raw line is stored as-is. The `level` label will be absent for those lines. + +### Disk usage + +Loki retains logs for **30 days** (configurable via `limits_config.retention_period` in `deploy/loki/loki.yaml`). Data is stored in the `loki-data` Docker volume. To check current volume size: + +```bash +docker system df -v | grep loki-data +``` + +To purge all Loki data and start fresh: +```bash +docker compose --profile observability down +docker volume rm errors-bitreport-pt_loki-data errors-bitreport-pt_promtail-positions +docker compose --profile observability up -d +``` + +## Configuration files + +| File | Purpose | +|---|---| +| `deploy/loki/loki.yaml` | Loki server — storage, schema, retention | +| `deploy/loki/promtail.yaml` | Promtail — Docker SD, JSON parsing, label extraction | +| `deploy/grafana/loki-logs-dashboard.json` | Grafana log visualisation dashboard | diff --git a/ingest-api/.env.example b/ingest-api/.env.example index 9162501..d670330 100644 --- a/ingest-api/.env.example +++ b/ingest-api/.env.example @@ -2,3 +2,5 @@ PORT=3041 DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/error_reporting INGEST_RATE_LIMIT_MAX=300 INGEST_RATE_LIMIT_WINDOW_MS=60000 +# Log verbosity: trace | debug | info | warn | error | fatal (default: info) +# LOG_LEVEL=info