ClickHouse system 日志表清理:TRUNCATE、关闭无用日志和 TTL 配置

ClickHouse 的 system.*_log 表在生产环境不加干预,几个月就能积累几十上百 GB。

空间占用查询

SELECT
    database,
    table,
    formatReadableSize(sum(bytes)) size
FROM system.parts
GROUP BY database, table
ORDER BY sum(bytes) DESC;

常见爆炸表:

典型症状
text_log大量 exception 或 debug 日志
trace_log开了 profile 或查询 trace
asynchronous_metric_logmetrics 刷新间隔太低
metric_log运行时间过长
part_log小批量高频 insert
query_log高频查询

立即清理

TRUNCATE TABLE system.text_log;
TRUNCATE TABLE system.trace_log;
TRUNCATE TABLE system.asynchronous_metric_log;
TRUNCATE TABLE system.metric_log;
TRUNCATE TABLE system.part_log;
TRUNCATE TABLE system.query_log;
TRUNCATE TABLE system.latency_log;
TRUNCATE TABLE system.processors_profile_log;

SYSTEM FLUSH LOGS;

TRUNCATE 后空间不会立刻全部回收(还有 deleted parts 和文件系统缓存),重启服务通常能完全释放:

systemctl restart clickhouse-server

关闭不需要的日志

编辑 /etc/clickhouse-server/config.xml/etc/clickhouse-server/config.d/*.xml

<!-- 关闭高噪音日志 -->
<text_log remove="1"/>
<trace_log remove="1"/>
<metric_log remove="1"/>
<asynchronous_metric_log remove="1"/>
<processors_profile_log remove="1"/>
<part_log remove="1"/>

重启生效:

systemctl restart clickhouse-server

生产建议:保留 query_log,用于慢查询分析。其余视需要选择性保留。

设置 TTL 限制保留天数

不想完全关闭,只保留最近几天:

<query_log>
    <database>system</database>
    <table>query_log</table>
    <flush_interval_milliseconds>7500</flush_interval_milliseconds>
    <ttl>event_date + INTERVAL 7 DAY DELETE</ttl>
</query_log>

part_log 异常:小批量写入问题

part_log 几千万行通常意味着:

  • 每条记录单独 INSERT(正确做法是批量几千到几万行)
  • Kafka consumer batch 配置太小
  • 频繁小事务导致 parts 积累、merge 压力大

查看各表的活跃 parts 数量:

SELECT
    table,
    count()
FROM system.parts
WHERE active
GROUP BY table
ORDER BY count() DESC;

正常表的 parts 数在百到千量级;如果单表几万 parts,说明写入模式有问题。

query_log 分析

高频查询:

SELECT
    query,
    count()
FROM system.query_log
GROUP BY query
ORDER BY count() DESC
LIMIT 20;

频繁报错的查询:

SELECT
    exception,
    count()
FROM system.query_log
WHERE type = 'ExceptionWhileProcessing'
GROUP BY exception
ORDER BY count() DESC
LIMIT 20;

不要直接删目录

rm -rf /var/lib/clickhouse/data/system/* 可能导致 metadata 不一致、启动失败或权限异常,优先使用 TRUNCATE、TTL 或 remove="1" 配置。