Bash script log file rotation

微笑、不失礼 提交于 2020-01-02 03:12:29

问题


My bash script produces a log file. Now i'd like to implement some log file rotation.
Let's say the first time it's called somelog.log, the next time it's renamed to somelog.log.1 and the new log file somelog.log.
The third time the new log is somelog.log again, but somelog.log.1 is renamed to somelog.log.2 and the old somelog.log to somelog.log.1.
I would be able to grant a maximum of eg 5.

Is this done before (sample script), any suggestions. I appreciate any advice.


回答1:


Try this bash function, it takes two parameters:

  1. number of maximum megabyte the file should exceed to be rotated (otherwise is let untouched)
  2. full path of the filename.

source:

function rotate () {
  # minimum file size to rotate in MBi:
  local MB="$1"
  # filename to rotate (full path)
  local F="$2"
  local msize="$((1024*1024*${MB}))"
  test -e "$F" || return 2

  local D="$(dirname "$F")"
  local E=${F##*.}
  local B="$(basename "$F" ."$E")"

  local s=

  echo "rotate msize=$msize file=$F -> $D | $B | $E"
  if [ "$(stat --printf %s "$F")" -ge $msize ] ; then
     for i in 8 9 7 6 5 4 3 2 1 0; do 
       s="$D/$B-$i.$E"
       test -e "$s" && mv $s "$D/$B-$((i+1)).$E"
  # emtpy command is need to avoid exit iteration if test fails:
       :;
     done &&
     mv $F $D/$B-0.$E
  else
     echo "rotate skip: $F < $msize, skip"
  fi
  return $?
}



回答2:


I've just made a bash script for that: https://github.com/lingtalfi/logrotator

It basically checks your log file's size, and if it exceeds an arbitrary threshold, it copies the log file into a log directory.

It's cron friendly, or you can use it manually too.

A typical command looks like that:

> ./logrotator.sh -f private/log -m {fileName}.{datetime}.txt -v


来源:https://stackoverflow.com/questions/3690015/bash-script-log-file-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!