I created a simple script that implements log rotation. It checks the log file size (say, out.log) if it exceeds 5MB limit. If it does then the script copies it to out1.log and clears out.log. But it also copies out1.log to out2.log, etc. So log files are kind of 'shifted' and contents of the last one is discarded. In this implementation I keep only 5 files (initial out.log and out[1-4].log).
I am not a Python programmer, although I find this language extremely useful for such kinds of tasks. I would like my code to be as much idiomatic as possible, so what can I change/improve in my script for this?
from os import listdir
from os.path import getsize, exists
from shutil import copyfile
from argparse import ArgumentParser
SIZE_5MB = 5e6
MAX_LOG_FILES_COUNT = 5
class LogRotator(object):
def __init__(self, prefix, suffix):
self.prefix = prefix
self.suffix = suffix
def __str__(self):
return "{}[x].{}".format(self.suffix, self.prefix)
def __touch(self, file_name):
open(file_name, 'w').close()
def rotate(self):
files = ["{}{}.{}".format(self.prefix, x + 1, self.suffix) for x in range(MAX_LOG_FILES_COUNT)]
[self.__touch(f) for f in files if not exists(f)]
current_log = "{}.{}".format(self.prefix, self.suffix)
if (getsize(current_log) < SIZE_5MB):
return
files.insert(0, current_log)
for i in range(len(files) - 1, 0, -1):
copyfile(files[i-1], files[i])
self.__touch(files[0])
if __name__ == '__main__':
parser = ArgumentParser(description="Rotate log files")
parser.add_argument("-prefix", help="log file prefix")
parser.add_argument("-suffix", help="log file suffix")
args = parser.parse_args()
logRotator = LogRotator(args.prefix, args.suffix)
logRotator.rotate()
{self.prefix}5.{suffix}. \$\endgroup\$