1
###############################################################################
4
# Author: Cody Precord <cprecord@editra.org> #
5
# Copyright: (c) 2010 Cody Precord <staff@editra.org> #
6
# License: wxWindows License #
7
###############################################################################
10
Editra Business Model Library: LogFile
12
Log file class for managing log files or other transient files that should
13
be purged after a given period of time.
17
__author__ = "Cody Precord <cprecord@editra.org>"
18
__svnid__ = "$Id: logfile.py 66868 2011-02-09 16:01:49Z CJP $"
19
__revision__ = "$Revision: 66868 $"
21
__all__ = ['LogFile',]
23
#--------------------------------------------------------------------------#
31
#--------------------------------------------------------------------------#
33
class LogFile(object):
35
def __init__(self, prefix, logdir=None):
37
@param prefix: filename prefix
38
@keyword logdir: abs path to log output dir
39
@note: if logdir is None then the system temp directory will be used
42
super(LogFile, self).__init__()
49
if self.logdir is None:
50
self.logdir = tempfile.gettempdir()
52
#---- Properties ----#
53
LogDirectory = property(lambda self: self.logdir,
54
lambda self, dname: setattr(self, 'logdir', dname))
55
Prefix = property(lambda self: self.prefix,
56
lambda self, prefix: setattr(self, 'prefix', prefix))
58
#---- Public Interface ----#
59
def WriteMessage(self, msg):
60
"""Append the message to the current log file
61
@param msg: string object
64
# Files are named as prefix_YYYY_MM_DD.log
65
logstamp = "%d_%d_%d" % time.localtime()[:3]
66
logname = "%s_%s.log" % (self.prefix, logstamp)
67
logpath = os.path.join(self.logdir, logname)
68
if os.path.exists(logpath):
73
# with open(logpath, opencmd) as handle:
74
# handle.write(msg.rstrip() + os.linesep)
76
handle = open(logpath, opencmd)
77
handle.write(msg.rstrip() + os.linesep)
82
def PurgeOldLogs(self, days):
83
"""Purge all log files older than n days
84
@param days: number of days
87
logpattern = re.compile("%s_[0-9]{4}_[0-9]{1,2}_[0-9]{1,2}.log" % self.prefix)
89
cdate = datetime.date(*time.localtime()[:3])
90
for path in os.listdir(self.logdir):
91
if logpattern.match(path):
92
ymd = [int(x) for x in path[len(self.prefix)+1:-4].split('_')]
93
fdate = datetime.date(*ymd)
96
fpath = os.path.join(self.logdir, path)
99
# Attempt to cleanup the old files