Class pour la gestion des logs.

From Tuxunix
Jump to: navigation, search

Code


   1.#!/usr/bin/python2.4
   2.# -*- coding: utf-8 -*-
   3.       
   4.#
   5.#@Name log.py
   6.#@Note Log prog and gzip compress log file
   7.#@Author pierre@tuxedo.fr
   8.#@Date 17/02/2009
   9.#@Depends
  10.#@Licence NO COPYRIGHT! GNU/GPL (RIGHT TO INFORMATION FOR ALL)
  11.#@Version 0.1
  12.#
  13.       
  14.import os, sys, time, datetime
  15.       
  16.#GLOBAL VAR
  17.#############
  18.LOGFILENAME='/var/log/nameProg.log'
  19.       
  20.class log(object):
  21.    """Write and read Access log sybilla applications"""
  22.       
  23.    def __init__(self, logFileName=LOGFILENAME):
  24.        self.logFileName = logFileName
  25.       
  26.    def readLog(self, file=LOGFILENAME):
  27.        if os.path.exists(file):
  28.            f=open(file)
  29.            data=f.read()
  30.            f.close()
  31.            if data != None or data != "":
  32.                return data
  33.            else:
  34.                return "No data!!"
  35.        else :
  36.           print "File %s doesn't exist !!!"%(file)
  37.       
  38.    def writeLog(self, msg):
  39.        if msg != "" :
  40.            try :
  41.                f=open(self.logFileName, 'a')
  42.                f.write(str(time.ctime()) + "\t" + msg +"\n")
  43.                f.close()
  44.            except IOError:
  45.                print "Error Open file %s"%(self.logFileName)
  46.        else:
  47.            print "Message vide!"
  48.       
  49.class GzipCompressor(object):
  50.    """Gzip compression"""
  51.    file_pattern = '%s.%d.gz'
  52.    def __init__(self):
  53.        pass
  54.       
  55.    def compress(self, fileName=LOGFILENAME):
  56.        if os.path.isfile(fileName):
  57.            dfn = fileName + '.1.gz'
  58.        if os.path.exists(dfn):
  59.            os.remove(dfn)
  60.        zf = gzip.GzipFile(dfn, 'wb')
  61.        zf.write(file(fileName, 'rb').read())
  62.        zf.close()
  63.        os.remove(fileName)
  64.       
  65.       
  66.    #Check size log file and compress if necessary
  67.    if os.path.exists(LOGFILENAME):
  68.        if os.path.getsize(LOGFILENAME) >= 566430:
  69.            comp = GzipCompressor()
  70.            comp.compress(LOGFILENAME)
  71.

By TuXedo