Ubuntu – How to gzip logs created by rotatelogs

apache-2.2gziplog-rotationUbuntu

I'm using rotatelogs to create my daily apache logs in format host.<day>.<month>.<year>.access.log. Now I want to gzip and move log to different directory after it's been finished. How to do that?

Update: There was a little mistake. logrotate -> rotatelogs

Best Answer

You could use rotatelogs option -p to use a program to compress the log after the rotation. (See for reference: https://httpd.apache.org/docs/2.4/programs/rotatelogs.html)

-p program

If given, rotatelogs will execute the specified program every time a new log file is opened. The filename of the newly opened file is passed as the first argument to the program. If executing after a rotation, the old log file is passed as the second argument. rotatelogs does not wait for the specified program to terminate before continuing to operate, and will not log any error code returned on termination. The spawned program uses the same stdin, stdout, and stderr as rotatelogs itself, and also inherits the environment.

Example:

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

compress.sh:

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