embed date in log's filename by default. Changed where logs are stored. Added rotate...
Tony Mack [Tue, 13 May 2008 01:09:18 +0000 (01:09 +0000)]
qaapi/qa/logger.py

index cea4ba4..7a139e1 100644 (file)
@@ -2,6 +2,7 @@ import os
 import traceback
 import time
 import sys
+import commands
 
 class Logfile:
     """
@@ -11,14 +12,47 @@ class Logfile:
         print >> logfile, data         
     """                
     def __init__(self, filename, date_in_filename = True):
+       
+       # whats the date
+       localtime = time.localtime()
+        (year, month, day) = localtime[:3]
+        date = "%(year)s.%(month)s.%(day)s" % locals()
+
+       # append date to filename
        if date_in_filename:
            if filename.find(".log") > -1:
                filename = filename.split(".log")[0] 
-           localtime = time.localtime()
-           (year, month, day) = localtime[:3]
-           filename = "%(filename)s-%(year)s.%(month)s.%(day)s.log" % locals()   
+           filename = "%(filename)s-%(date)s.log" % locals()
+       
+       filename_parts = filename.split(os.sep)
+       # Add directory (qaapi) to files path
+       if 'qaapi' not in filename_parts: 
+           filename_parts.insert(len(filename_parts)-1, 'qaapi')
+       # Add directory(today's date) to file's path
+       if date not in filename_parts:
+           filename_parts.insert(len(filename_parts)-1, date)
+        
+       # Make sure file's parent directory exists
+       self.dir = filename_dir = os.sep + os.sep.join(filename_parts[:-1]) + os.sep
+       filename = os.sep + os.sep.join(filename_parts) 
+       (status, output) = commands.getstatusoutput("mkdir -p %(filename_dir)s" % locals())
         self.filename = filename
 
+    def rotate(self):
+       if os.path.isfile(self.filename):
+           (status, output) = utils.commands("ls %s*" % self.filename)
+           files = output.split("\n")
+           files.sort()
+           lastfile = files[-1:][0]
+           index = lastfile.split(self.logfile.filename)[1].replace(".", "")
+       
+           if not index:
+               index = "1"
+           else:
+               index = str(int(index) +1)
+           utils.commands("mv %s %s.%s" % (self.filename, self.filename, index))               
+               
+
     def write(self, data):
         try:
             fd = os.open(self.filename, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0644)