日志切分神器--logrotate

Blog:博客园 我的nginx

概述

还在本身写定时切分日志的脚本?试试系统自带的logrotate工具吧!bash

logrotate是一个日志文件管理工具。用于分割日志文件,删除旧的日志文件,并建立新的日志文件,起到转储的做用,便于节省磁盘空间。工具

配置

配置文件

Linux系统默认安装logrotate,默认配置文件以下:post

  • /etc/logrotate.conf:主配置文件,logrotate.d是一个目录,该目录里的全部文件都会被主动的读入/etc/logrotate.conf中执行。
  • /etc/logrotate.d/:用于存放不一样程序自定义切分配置

运行原理

Logrotate是基于CRON来运行的,其脚本是/etc/cron.daily/logrotate,日志轮转是系统自动完成的。测试

实际运行时,Logrotate会调用配置文件/etc/logrotate.conf。能够在/etc/logrotate.d目录里放置自定义好的配置文件,用来覆盖Logrotate的缺省值。debug

/etc/cron.daily/logrotate脚本以下:日志

#!/bin/sh

/usr/sbin/logrotate /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit $EXITVALUE

配置参数说明

配置参数 说明
create 自动建立新的日志文件,新的日志文件具备和原来的文件相同的权限;由于日志被更名,所以要建立一个新的来继续存储以前的日志
rotate n 保留多少个日志文件(轮转几回),n能够是0,1,2,3...,若是n为0,则没有备份。
dateext 就是切割后的日志文件以当前日期为格式结尾
compress 是否经过gzip压缩转储之后的日志文件,如xxx.log-20201111.gz
nocompress 不作gzip压缩处理,与compress互斥
missingok 在日志轮循期间,任何错误将被忽略,例如“文件没法找到”之类的错误。
notifempty 若是日志文件为空,轮循不会进行。
create 0664 nginx root 以指定的权限建立全新的日志文件,同时logrotate也会重命名原始日志文件。
postrotate 在全部其它指令完成后,postrotate里面指定的命令将被执行。

lograte命令

语法格式以下:code

logrotate [OPTION...] <configfile>

参数说明

参数 说明
-d debug模式,测试配置文件是否有错误。
-f 强制转储文件。
-m 压缩日志后,发送日志到指定邮箱。
-s 使用指定的状态文件。
-v 显示转储过程。

案例

以nginx日志切分为例,建立/etc/logrotate.d/nginxorm

/var/log/nginx/*log {
    create 0664 nginx root
    daily
    rotate 10
    dateext
    missingok
    notifempty
    compress
    sharedscripts
    postrotate
        /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}

手动强制切分日志:blog

/usr/sbin/logrotate -d -f /etc/logrotate.d/nginx

效果以下:

image-20201112110725767