如何gzip由rotatelogs创建的日志

Pom*_*oma 9 ubuntu gzip apache-2.2 log-rotation

我正在使用rotatelogs 以格式创建我的每日apache 日志host.<day>.<month>.<year>.access.log。现在我想在完成后 gzip 并将日志移动到不同的目录。怎么做?

更新:有一个小错误。logrotate->rotatelogs

小智 8

您可以使用rotatelogs选项-p来使用程序在轮换后压缩日志。(参考:https : //httpd.apache.org/docs/2.4/programs/rotatelogs.html

-p 程序

如果给定,rotatelogs 将在每次打开新的日志文件时执行指定的程序。新打开的文件的文件名作为第一个参数传递给程序。如果在轮换后执行,则旧日志文件将作为第二个参数传递。rotatelogs 在继续操作之前不会等待指定的程序终止,并且不会记录终止时返回的任何错误代码。生成的程序使用与rotatelogs 本身相同的stdin、stdout 和stderr,并且还继承了环境。

例子:

CustomLog "|bin/rotatelogs -p '/path/to/compress.sh' -l /var/log/logfile.%Y.%m.%d 86400"

压缩文件

#!/bin/bash
file_to_compress="${2}"
compress_exit_code=0

if [[ "${file_to_compress}" ]]; then
    echo "Compressing ${file_to_compress} ..."
    tar --gzip --create --file "${file_to_compress}.tar.gz" "${file_to_compress}"

    compress_exit_code=${?}

    if [[ ${compress_exit_code} == 0 ]]; then
        echo "File ${file_to_compress} was compressed."
    else
        echo "Error compressing file ${file_to_compress} (tar exit code: ${compress_exit_code})."
    fi
fi

exit ${compress_exit_code}
Run Code Online (Sandbox Code Playgroud)


Pom*_*oma 5

我想出了以下脚本

#!/bin/sh
for file in $(ls /var/log/apache2/*.$(date +"%y.%m.%d" --date="1 day ago").access.log); do
    gzip $file
    mv $file.gz /var/log/apache2/archive
done;
Run Code Online (Sandbox Code Playgroud)

并在 cron 条目之后

15 0    0 0 0   root    /mypath/myscript.sh
Run Code Online (Sandbox Code Playgroud)