ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 概述 - 日志切割工具 - logrotate可以实现自动轮替、删除、压缩和mail日志的功能 指令 ``` # logrotate --help Usage: logrotate [OPTION...] <configfile> -d, --debug Don't do anything, just test (implies -v) 不做实际处理,仅调试 -f, --force Force file rotation 强制执行,忽视参数要求 -m, --mail=command Command to send mail (instead of `/bin/mail') 发送mail -s, --state=statefile Path of state file 查看状态文件 -v, --verbose Display messages during rotation 轮替一次,并显示轮替过程信息 --version Display version information 显示logrotate版本 Help options: -?, --help Show this help message --usage Display brief usage message ``` 配置文件 ``` /etc/logrotate.conf /etc/logrotate.d ``` ## 常用参数 ``` daily 每天轮替一次 weekly 每周轮替一次 monthly 每月轮替一次 yearly 每年轮替一次 rotate 保留几个轮替日志文件 ifempty 不论日志是否空,都进行轮替 notifempty 若日志为空,则不进行轮替 create 旧日志文件轮替后创建新的日志文件 copytruncate 用于还在打开中的日志文件,把当前日志备份并截断 nocopytruncate 备份日志文件但是不截断 size 日志达到多少后进行rotate minsize 文件容量一定要超过多少后才进行rotate nocompress 轮替但不进行压缩 compress 压缩轮替文件 dateext 轮替旧日志文件时,文件名添加-%Y %m %d形式日期,可用dateformat选项扩展配置。 nodateext 旧日志文件不使用dateext扩展名,后面序数自增如"*.log.1" dateformat 只允许%Y %m %d和%s指定符。注意:系统时钟需要设置到2001-09-09之后,%s才可以正确工作 sharedscripts 作用域下文件存在至少有一个满足轮替条件的时候,执行一次prerotate脚本和postrotate脚本。 prerotate/endscript 在轮替之前执行之间的命令,prerotate与endscript成对出现。 postrotate/endscript 在轮替之后执行之间的命令,postrotate与endscript成对出现。 olddir 将轮替的文件移至指定目录下 missingok 如果日志文件不存在,继续进行下一个操作,不报错 ``` ## 示例 ### Hello World ``` #/etc/logrotate.d/test /test/log/*.log{ daily rotate 2 size 1M create compress missingok dateext olddir /test/rotate } ``` - 每天对/test/log/目录下后缀为“.log”的且 大小超过1MB 的文件进行轮替 - 文件后缀为 ”-20171124“ 。压缩轮替后的文件,并将该文件移到”/test/rotate“目录下, - 一个原日志文件最多仅有2个对应轮替日志文件,若轮替日志大于设定的值则删除之前较早的轮替日志文件。 - 创建新的日志文件。若/test/log/目录下文件名以”.log“结尾的文件不存在,不报错 **搭配crontab处理** ``` * */1 * * * root /usr/sbin/logrotate -v /etc/logrotate.d/test ```