技能创建器
skill-creator
创建、改进和评估自定义技能,把专业流程转化为可重复使用的 AI 能力。
configure-log-aggregation【数据与研究】Set up centralized log aggregation with Loki and Promtail (or ELK stack), including log parsing, label extraction, retention policies, and integration with metrics for correlation. Use when consolidating logs from multiple services into a searchable system, replacing local log files with centralized queryable storage, correlating logs with metrics an…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
以 Loki/Promtail 或 ELK 施中誌收、析、查為行之見。
見 Extended Examples 以全設檔。
依需擇 Loki(Prometheus 式)或 ELK(Elasticsearch 式)。
Loki 之善:
ELK 之善:
此引專於 Loki + Promtail(多數現代宜)。
決之準:
Use Loki if:
- You want label-based queries similar to Prometheus
- Storage costs are a concern (Loki indexes only labels)
- You already use Grafana for metrics
- Kubernetes/container-native deployment
Use ELK if:
- You need full-text search across all log content
- You have complex log parsing and enrichment requirements
- You require advanced analytics and aggregations
- Legacy systems with existing Logstash pipelines
得: 明擇依需,團下合之裝品。
敗則:
裝設 Loki 附合存後端。
Docker Compose 部(docker-compose.yml):
version: '3.8'
services:
loki:
image: grafana/loki:2.9.0
ports:
- "3100:3100"
volumes:
- ./loki-config.yml:/etc/loki/local-config.yaml
- loki-data:/loki
command: -config.file=/etc/loki/local-config.yaml
restart: unless-stopped
promtail:
image: grafana/promtail:2.9.0
volumes:
- ./promtail-config.yml:/etc/promtail/config.yml
- /var/log:/var/log:ro
- /var/lib/docker/containers:/var/lib/docker/containers:ro
command: -config.file=/etc/promtail/config.yml
restart: unless-stopped
depends_on:
- loki
volumes:
loki-data:
Loki 設(loki-config.yml):
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
# ... (see EXAMPLES.md for complete configuration)
產附 S3 存:
storage_config:
aws:
s3: s3://us-east-1/my-loki-bucket
s3forcepathstyle: true
boltdb_shipper:
active_index_directory: /loki/index
cache_location: /loki/cache
shared_store: s3
得: Loki 啟成,健察於 http://localhost:3100/ready 過,誌依留策存。
敗則:
docker logs lokidocker run grafana/loki:2.9.0 -config.file=/etc/loki/local-config.yaml -verify-config設 Promtail 刮誌送 Loki 附取標。
Promtail 設(promtail-config.yml):
server:
http_listen_port: 9080
grpc_listen_port: 0
positions:
filename: /tmp/positions.yaml
# ... (see EXAMPLES.md for complete configuration)
Promtail 之要:
得: Promtail 刮設誌檔,標正施,誌經 LogQL 查於 Loki 可見。
敗則:
docker logs promtaildocker exec promtail ls /var/logcurl http://localhost:9080/metrics | grep promtailcat /tmp/positions.yaml學 LogQL 之法為濾聚誌。
基查:
# All logs from a job
{job="app"}
# Logs with specific label values
{job="app", level="error"}
# Regex filter on log line content
{job="app"} |~ "authentication failed"
# Case-insensitive regex
{job="app"} |~ "(?i)error"
# Line filter (doesn't parse, just includes/excludes)
{job="app"} |= "user" # Contains "user"
{job="app"} != "debug" # Doesn't contain "debug"
析與濾:
# JSON parsing
{job="app"} | json | level="error"
# Regex parsing with named groups
{job="app"} | regexp "user_id=(?P<user_id>\\d+)" | user_id="12345"
# Logfmt parsing (key=value format)
{job="app"} | logfmt | level="error", service="auth"
# Pattern parsing
{job="nginx"} | pattern `<ip> - <user> [<timestamp>] "<method> <path> <protocol>" <status> <size>` | status >= 500
聚(自誌得量):
# Count log lines per level
sum by (level) (count_over_time({job="app"}[5m]))
# Rate of error logs
rate({job="app", level="error"}[5m])
# Bytes processed per service
sum by (service) (bytes_over_time({job="app"}[1h]))
# Average request duration from logs
avg_over_time({job="app"} | json | unwrap duration [5m])
# Top 10 error messages
topk(10, sum by (message) (count_over_time({level="error"} [1h])))
以取欄濾:
# Find specific trace in logs
{job="app"} | json | trace_id="abc123def456"
# HTTP 5xx errors from nginx
{job="nginx"} | pattern `<_> "<_> <_> <_>" <status> <_>` | status >= 500
# Failed authentication attempts
{job="app"} | json | message=~"authentication failed" | user_id != ""
以此建 Grafana Explore 查或板項。
得: 查返期誌,濾正行,聚自誌生量。
敗則:
curl http://localhost:3100/loki/api/v1/labelscurl http://localhost:3100/loki/api/v1/label/{label_name}/values連誌於 Prometheus 量與散跡為一察。
加 trace ID 於誌(應儀):
# Python with OpenTelemetry
import logging
from opentelemetry import trace
logger = logging.getLogger(__name__)
def handle_request():
span = trace.get_current_span()
trace_id = span.get_span_context().trace_id
logger.info(
"Processing request",
extra={"trace_id": format(trace_id, "032x")}
)
// Go with OpenTelemetry
import (
"go.opentelemetry.io/otel/trace"
"go.uber.org/zap"
)
func handleRequest(ctx context.Context) {
span := trace.SpanFromContext(ctx)
traceID := span.SpanContext().TraceID().String()
logger.Info("Processing request",
zap.String("trace_id", traceID),
)
}
設 Grafana 資鏈自量至誌:
於 Prometheus 板欄設:
{
"fieldConfig": {
"defaults": {
"links": [
{
"title": "View Logs",
"url": "/explore?left={\"datasource\":\"Loki\",\"queries\":[{\"refId\":\"A\",\"expr\":\"{job=\\\"app\\\",instance=\\\"${__field.labels.instance}\\\"} |= `${__field.labels.trace_id}`\"}],\"range\":{\"from\":\"${__from}\",\"to\":\"${__to}\"}}",
"targetBlank": false
}
]
}
}
}
設 Grafana 資鏈自誌至跡:
於 Loki 資源設:
datasources:
- name: Loki
type: loki
url: http://loki:3100
jsonData:
derivedFields:
- datasourceName: Tempo
matcherRegex: "trace_id=(\\w+)"
name: TraceID
url: "${__value.raw}"
於 Grafana Explore 連誌:
得: 點量開相關誌,誌中 trace ID 連至跡視,量/誌/跡一板導。
敗則:
設留策與縮以治存本。
依流之留(於 Loki 設):
limits_config:
retention_period: 720h # Global default: 30 days
# Per-tenant retention (requires multi-tenancy enabled)
per_tenant_override_config: /etc/loki/overrides.yaml
# overrides.yaml
overrides:
production:
retention_period: 2160h # 90 days for production
staging:
retention_period: 360h # 15 days for staging
development:
retention_period: 168h # 7 days for dev
依流標之留(需 compactor):
compactor:
working_directory: /loki/compactor
shared_store: filesystem
compaction_interval: 10m
retention_enabled: true
retention_delete_delay: 2h
# ... (see EXAMPLES.md for complete configuration)
先(小數高先)定多配之則施何者。
壓設:
chunk_store_config:
chunk_cache_config:
enable_fifocache: true
fifocache:
max_size_bytes: 1GB
ttl: 24h
# ... (see EXAMPLES.md for complete configuration)
監留:
# Check chunk stats
curl http://localhost:3100/loki/api/v1/status/chunks | jq
# Check compactor metrics
curl http://localhost:3100/metrics | grep loki_compactor
# Verify deleted chunks
curl http://localhost:3100/metrics | grep loki_boltdb_shipper_retention_deleted
得: 舊誌依留策自刪,存穩,縮減索量。
敗則:
docker logs loki | grep compactordu -sh /loki/curl http://localhost:3100/readyretention_enabled: true 與 retention_deletes_enabled: true。ingestion_rate_mb 與 ingestion_burst_size_mb。correlate-observability-signals - 以 trace ID 跨量誌跡之調build-grafana-dashboards - 視自誌得量而建誌板setup-prometheus-monitoring - 量供何時查誌之境於事中instrument-distributed-tracing - 加 trace ID 於誌以連散跡