Log rotating with a Bash script

前端 未结 5 1562
时光取名叫无心
时光取名叫无心 2021-02-01 20:09

I have the following issue:

I have an application, which continuously produces output to stderr and stdout. The output of this application is captured in a logfile (the

5条回答
  •  孤城傲影
    2021-02-01 20:28

    First of all, you really should not reinvent the square wheel here. Your peers are probably against rotating the logs on daily schedule which automatically applies to all scripts in /etc/logrotate.d/ - this can be avoided by placing the script elsewhere.


    Now, the standard approach to log rotation (that is implemented in logrotate) can be implemented by any other facility just as well. E.g. here's a sample implementation in bash:

    MAXLOG=
    for i in `seq $((MAXLOG-1)) -1 1`; do
        mv "log."{$i,$((i+1))}    #will need to ignore file not found errors here
    done 
    mv log log.1    # since a file descriptor is linked to an inode rather than path,
                    #if you move (or even remove) an open file, the program will continue
                    #to write into it as if nothing happened
                    #see https://stackoverflow.com/questions/5219896/how-do-the-unix-commands-mv-and-rm-work-with-open-files
    
    

    The last item is done by sending SIGHUP or (less often) SIGUSR1 and having a signal handler in the daemon that replaces the corresponding file descriptor or variable. This way, the switch is atomic, so there's no interruption in logging availability. In bash, this would look like:

    trap { exec &>"$LOGFILE"; } HUP
    

    The other approach is to make the writing program itself keep track of the log size each time it writes to it and do the rotation. This limits your options in where you can write to and what rotation logic is to what the program itself supports. But it has the benefit of being a self-contained solution and checking the log size at each write rather than on schedule. Many languages' standard libraries have such a facility. As a drop-in solution, this is implemented in Apache's rotatelogs:

     2>&1 | rotatelogs   
    

提交回复
热议问题