Ir para o conteúdo

Log Size Control

Aqui está um script, que funciona em Windows e em Linux, e que ajuda a "controlar" o tamanho dos ficheiros de log que queira monitorizar.

Nota: O script vai buscar os dados dos logs que querem monitorizar ao ficheiro loglist.data

import os, bz2, sys

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Log Size Control 100% cross platform (windows/linux);   #
#               Take the files for array                  #
#               Check the size if its bigger them         #
#               max_size compress to bz2 file             #
#                                                         #
#   Made by Rui Gomes - 29-07-2008                        #
#                                                         #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

max_size=20000  #define the max size of the log in kb

try:
    logs=open("loglist.data", "r").readlines() #catch the data in the data file
except:
    print "Its not possible read the config file loglist.data" #if the file its not present or dont have rights to read him
    sys.exit(1)

for log in logs:
    if os.path.isfile(log): #if the line in the loglist.data its a file     

        log=log.strip("\n") #Take out the change line character
        log=os.path.normpath(log) #make it easy you can put / or \ gonna always work in both systems (windows/linux)
        size=os.path.getsize(log)#get the size of the file
        sizekb=size/1024 #for more precision use sizekb=float(size)/1024

        if sizekb >= max_size: #test if the file its big or not...

            try:  #test if the file its free

                os.rename(log, "%s.bck"%log) #rename the file log
                uncompress_data=open("%s.bck"%log, "rb").read()
                compress_output=bz2.compress(uncompress_data) #compress the renamed file

                file_output=open(log+".bz", 'wb') #
                file_output.write(compress_output)# create the compress file of the log
                file_output.close()               #

                os.unlink("%s.bck"%log) #remove the backup file

            except IOError:

                print "Error file lock"
                pass #if the file its not free skip the compression to the next time, and move to the next file

            except:
                print "Unknown Error" #some vodoo happen!!!
                pass #go to the next file

    else:#if the line in the loglist.data its not a file  
        print "%s -> This file doesn't exist\n" %log