zoukankan      html  css  js  c++  java
  • 日志切分神器--logrotate

    Blog:博客园 个人

    概述

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

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

    配置

    配置文件

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

    • /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的缺省值。

    /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命令

    语法格式如下:

    logrotate [OPTION...] <configfile>
    

    参数说明

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

    案例

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

    /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
    }
    

    手动强制切分日志:

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

    效果如下:

    image-20201112110725767

  • 相关阅读:
    OSX安装nginx和rtmp模块(rtmp直播服务器搭建)
    用runtime来重写Coder和deCode方法 归档解档的时候使用
    Homebrew安装卸载
    Cannot create a new pixel buffer adaptor with an asset writer input that has already started writing'
    OSX下面用ffmpeg抓取桌面以及摄像头推流进行直播
    让nginx支持HLS
    iOS 字典转json字符串
    iOS 七牛多张图片上传
    iOS9UICollectionView自定义布局modifying attributes returned by UICollectionViewFlowLayout without copying them
    Xcode6 iOS7模拟器和Xcode7 iOS8模拟器离线下载
  • 原文地址:https://www.cnblogs.com/Rohn/p/13974661.html
Copyright © 2011-2022 走看看