Loki 本身不提供命令行或 HTTP API 删除特定日志,但你可以通过配置 retention_period 来实现日志自动清理。
yaml
loki:
config:
table_manager:
retention_deletes_enabled: true
retention_period: 168h # 保留7天
适用于 boltdb-shipper 或 chunk store。
如果你用的是 filesystem 模式,还可以这样:
yaml
loki:
config:
schema_config:
configs:
- from: 2020-10-24
store: boltdb-shipper
object_store: filesystem
schema: v11
index:
prefix: index_
period: 24h
limits_config:
retention_period: 168h
compactor:
shared_store: filesystem
retention_enabled: true #启用日志保留与删除逻辑。必须开启它,Loki 才会按照 retention_period 进行清理。
retention_delete_delay: 15s #表示当日志过期后,再等 2 小时才会执行删除。这可以防止日志刚刚到期就被清掉,适用于边界时间处理。
retention_delete_worker_count: 150 #控制同时并发执行的清理 worker 数量,数字越大,清理越快,但资源消耗也更多。
然后部署 Loki 的 compactor 组件(默认部署,只要改配置就可以),它负责删除超过保留期的日志。
如果配置成功,观察 loki 日志会有如下输出
bash
level=info ts=2025-05-23T08:27:04.059284074Z caller=index_set.go:185 msg="cleaning up unwanted indexes from table index_xxx"
还有一个日志接收参数,这里顺带提一下
reject_old_samples_max_age:
168h 不是日志的保留期限,而是一个防止旧数据写入的限制。它的作用是:
yaml
loki:
config:
limits_config:
reject_old_samples: true
reject_old_samples_max_age: 168h #表示 Loki 拒绝接收时间戳早于当前时间减去该值的日志样本。