温馨提示×

怎么分割linux大日志文件

小樊
47
2026-09-26 16:11:32
栏目: 智能运维

在 Linux 下,大日志文件分割常见有几种方式,取决于你的目的(按大小、按行数、按时间、实时滚动等)。下面按使用场景给你总结。


一、按【文件大小】分割(最常用)

1️⃣ split 命令(推荐)

split -b 100M access.log access_part_
  • -b 100M:每个文件 100MB
  • 生成:
    access_part_aa
    access_part_ab
    access_part_ac
    

按 行数 分割:

split -l 100000 access.log access_part_

自定义后缀长度:

split -b 100M -d access.log access_part_

生成:

access_part_00
access_part_01

二、按【时间 / 日期】分割日志(适合 nginx、tomcat)

1️⃣ logrotate(生产环境标准方案)

配置文件示例:

/var/log/nginx/access.log {
    daily
    rotate 30
    compress
    missingok
    notifempty
    create 0644 nginx nginx
    sharedscripts
    postrotate
        systemctl reload nginx
    endscript
}

常用参数:

  • daily / weekly / monthly
  • size 100M(超过才切)
  • compress(gzip)
  • rotate N(保留份数)

三、按【时间段】从日志中提取

例如提取某天的日志:

grep "2026-01-21" access.log > access_2026-01-21.log

提取某小时:

awk '$4 >= "[21/Jan/2026:10" && $4 < "[21/Jan/2026:11"' access.log

四、实时滚动日志(不中断服务)

tail -f + split

tail -f access.log | split -b 50M - access_live_

或结合 logrotate 更稳妥。


五、大文件处理建议(很重要)

✅ 不要直接 vim 大日志
✅ 优先:

  • split
  • grep
  • awk
  • zcat(压缩日志)

查看大文件前几行:

head -n 100 access.log

统计行数(快):

wc -l access.log

六、推荐组合方案(实战)

场景 方案
临时分析 split -b
生产服务 logrotate
按天查问题 grep 日期
超大数据 awk + split

如果你能告诉我:

  • 日志类型(nginx / java / 系统日志)
  • 想要按 大小 / 天 / 行数
  • 是否线上运行

我可以给你精准命令示例。

0 踩