Compress and Move Log Files
Sometimes log files bog a system down. For one of our servers, I made this little Python script that compresses (via WinRAR) the log files in a directory, and then moves them to a backup location. The only little catch is that I wanted to leave the latest log files for in that directory. Log files are created daily, so the the latest log files have a datestamp of today. Here’s how I did it.
First Create the Python Script:
import os import datetime dateStamp = datetime.datetime.now().strftime("%Y-%m-%d") imsLogPath = 'd:\\LogFiles\\' # Don't use a mapped drive but use UNC for network drives. Task Schedule seems to choke when it calls Python. newRARPath = '"\\\\192.168.1.2\\Root\\backups\\' + dateStamp + '.rar"' rarPath = '"C:\\Program Files\\WinRAR\\rar.exe" a -m5 ' + newRARPath # Get Latest Files smtpLatest = os.popen(r"dir /od /a-d /b " + imsLogPath + "SMTP*.log").read().splitlines()[-1] postLatest = os.popen(r"dir /od /a-d /b " + imsLogPath + "POST*.log").read().splitlines()[-1] ischedLatest = os.popen(r"dir /od /a-d /b " + imsLogPath + "iSched*.log").read().splitlines()[-1] relayLatest = os.popen(r"dir /od /a-d /b " + imsLogPath + "Relay*.log").read().splitlines()[-1] qengLatest = os.popen(r"dir /od /a-d /b " + imsLogPath + "Qeng*.log").read().splitlines()[-1] # Get List of All Files allFiles = os.popen(r"dir /od /a-d /b " + imsLogPath + "*.log").read().splitlines() # Remove Latest Files from All Files List allFiles.remove( smtpLatest ) allFiles.remove( postLatest ) allFiles.remove( ischedLatest ) allFiles.remove( relayLatest ) allFiles.remove( qengLatest ) # allFiles Array Has the list of files # Flatten Array allFiles to be used as a parameter in system command flatLogPathList = "" for filenameWithPath in allFiles: flatLogPathList = flatLogPathList + imsLogPath + filenameWithPath + " " # Execute WinRar path = rarPath + " " + flatLogPathList.rstrip() os.system( '"' + path + '"' ) # Delete all log files os.system( '"del ' + flatLogPathList.rstrip() + '"' )
Then I set up the Scheduled Task:
With these Settings: