description: 使用LogQL查询和分析Grafana Loki中的日志 allowed-tools:
- Bash
Loki日志分析技能
查询和分析来自Grafana Loki的日志,用于事件调查和调试。
调查工作流程
- 列出可用标签 以了解可查询内容
- 获取统计信息 以了解日志量和错误率
- 采样日志 以查看代表性条目
- 使用LogQL查询特定模式
LogQL快速参考
流选择器(必需)
{app="frontend"} # 精确匹配
{namespace=~"prod-.*"} # 正则表达式匹配
{container!="sidecar"} # 不等于
{pod=~".+"} # 任何非空值
行过滤器
{app="api"} |= "error" # 包含 "error"
{app="api"} != "debug" # 不包含
{app="api"} |~ "error|warn" # 正则表达式匹配
{app="api"} !~ "health|ready" # 正则表达式不匹配
解析器和标签提取
{app="api"} | json # 解析JSON日志
{app="api"} | logfmt # 解析logfmt格式
{app="api"} | pattern `<ip> - <_> [<timestamp>] "<method> <path>"`
{app="api"} | json | level="error" # 在提取的标签上过滤
聚合(度量查询)
# 每秒日志计数
rate({app="api"}[5m])
# 每分钟错误计数
sum(rate({app="api"} |= "error" [1m])) by (pod)
# 处理字节数
bytes_rate({app="api"}[5m])
# 唯一值计数
count_over_time({app="api"} | json | __error__="" [1h])
可用脚本
list_labels.py
列出可用标签及其值。
python scripts/list_labels.py
python scripts/list_labels.py --label app
python scripts/list_labels.py --label namespace --json
get_statistics.py
获取日志量和错误统计信息。
python scripts/get_statistics.py --selector '{app="frontend"}'
python scripts/get_statistics.py --selector '{namespace="production"}' --lookback 2
python scripts/get_statistics.py --selector '{app=~"api.*"}' --json
sample_logs.py
获取样本日志条目。
python scripts/sample_logs.py --selector '{app="frontend"}'
python scripts/sample_logs.py --selector '{app="api"}' --filter "error"
python scripts/sample_logs.py --selector '{namespace="prod"}' --limit 50 --json
query_logs.py
执行原始LogQL查询。
python scripts/query_logs.py '{app="api"} |= "error" | json'
python scripts/query_logs.py 'rate({app="api"} |= "error" [5m])' --type metric
python scripts/query_logs.py '{app="api"}' --limit 100 --lookback 2 --json
环境变量
LOKI_BASE_URL: 代理端点(生产环境)LOKI_URL: 直接Loki URL(测试环境,例如 http://loki:3100)
常见调查模式
在服务中查找错误
python scripts/sample_logs.py --selector '{app="api"}' --filter "error|exception|fail"
比较不同Pod之间的错误率
python scripts/query_logs.py 'sum(rate({app="api"} |= "error" [5m])) by (pod)' --type metric
查找慢请求(如果使用包含持续时间的JSON日志)
python scripts/query_logs.py '{app="api"} | json | duration > 1000' --limit 20
围绕时间戳关联日志
python scripts/query_logs.py '{app="api"}' --start "2024-01-15T10:30:00Z" --end "2024-01-15T10:35:00Z"