Package dogtail :: Module logging
[hide private]
[frames] | no frames]

Source Code for Module dogtail.logging

  1  # -*- coding: utf-8 -*- 
  2  """ 
  3  Logging facilities 
  4   
  5  Authors: Ed Rousseau <rousseau@redhat.com>, Zack Cerza <zcerza@redhat.com, David Malcolm <dmalcolm@redhat.com> 
  6  """ 
  7   
  8  __author__ = """Ed Rousseau <rousseau@redhat.com>, 
  9  Zack Cerza <zcerza@redhat.com, 
 10  David Malcolm <dmalcolm@redhat.com> 
 11  """ 
 12  import os 
 13  import sys 
 14  import time 
 15  import datetime 
 16  from config import config 
 17  import codecs 
 18   
 19  # Timestamp class for file logs 
20 -class TimeStamp:
21 """ 22 Generates timestamps tempfiles and log entries 23 """
24 - def __init__(self):
25 self.now = "0" 26 self.timetup = time.localtime()
27
28 - def zeroPad(self, int, width = 2):
29 """ 30 Pads an integer 'int' with zeroes, up to width 'width'. 31 32 Returns a string. 33 34 It will not truncate. If you call zeroPad(100, 2), '100' will be returned. 35 """ 36 if int < 10 ** width: 37 return ("0" * (width - len(str(int))) ) + str(int) 38 else: 39 return str(int)
40 41 # file stamper
42 - def fileStamp(self, filename, addTime = True):
43 """ 44 Generates a filename stamp in the format of filename_YYYYMMDD-hhmmss. 45 A format of filename_YYYYMMDD can be used instead by specifying addTime = False. 46 """ 47 self.now = filename.strip() + "_" 48 self.timetup = time.localtime() 49 50 # Should produce rel-eng style filestamps 51 # format it all pretty by chopping the tuple 52 fieldCount = 3 53 if addTime: fieldCount = fieldCount + 3 54 for i in range(fieldCount): 55 if i == 3: self.now = self.now + '-' 56 self.now = self.now + self.zeroPad(self.timetup[i]) 57 return self.now
58 59 # Log entry stamper
60 - def entryStamp(self):
61 """ 62 Generates a logfile entry stamp of YYYY.MM.DD HH:MM:SS 63 """ 64 self.timetup = time.localtime() 65 66 # This will return a log entry formatted string in YYYY.MM.DD HH:MM:SS 67 for i in range(6): 68 # put in the year 69 if i == 0: 70 self.now = str(self.timetup[i]) 71 # Format Month and Day 72 elif i == 1 or i == 2: 73 self.now = self.now + "." + self.zeroPad(self.timetup[i]) 74 else: 75 x = self.timetup[i] 76 # make the " " between Day and Hour and put in the hour 77 if i == 3: 78 self.now = self.now + " " + self.zeroPad(self.timetup[i]) 79 # Otherwise Use the ":" divider 80 else: 81 self.now = self.now + ":" + self.zeroPad(self.timetup[i]) 82 return self.now
83
84 -class Logger:
85 """ 86 Writes entries to standard out. 87 """ 88 stamper = TimeStamp()
89 - def __init__(self, logName, file = False, stdOut = True):
90 """ 91 name: the name of the log 92 file: The file object to log to. 93 stdOut: Whether to log to standard out. 94 """ 95 self.logName = logName 96 self.stdOut = stdOut 97 self.file = file # Handle to the logfile 98 if not self.file: return 99 100 scriptName = config.scriptName 101 if not scriptName: scriptName = 'log' 102 self.fileName = scriptName 103 104 # check to see if we can write to the logDir 105 if os.path.isdir(config.logDir): 106 self.findUniqueName() 107 else: 108 # If path doesn't exist, raise an exception 109 raise IOError, \ 110 "Log path %s does not exist or is not a directory" % logDir
111
112 - def findUniqueName(self):
113 # generate a logfile name and check if it already exists 114 self.fileName = config.logDir + self.stamper.fileStamp(self.fileName) \ 115 + '_' + self.logName 116 i = 0 117 while os.path.exists(self.fileName): 118 # Append the pathname 119 if i == 0: 120 self.fileName = self.fileName + "." + str(i) 121 else: 122 logsplit = self.fileName.split(".") 123 logsplit[-1] = str(i) 124 self.fileName = ".".join(logsplit) 125 i += 1
126
127 - def createFile(self):
128 # Try to create the file and write the header info 129 print "Creating logfile at %s ..." % self.fileName 130 self.file = codecs.open(self.fileName, mode = 'wb', encoding = \ 131 'utf-8') 132 self.file.write("##### " + os.path.basename(self.fileName) + '\n') 133 self.file.flush()
134
135 - def log(self, message, newline = True, force = False):
136 """ 137 Hook used for logging messages. Might eventually be a virtual 138 function, but nice and simple for now. 139 140 If force is True, log to a file irrespective of config.logDebugToFile. 141 """ 142 message = message.decode('utf-8', 'replace') 143 144 # Try to open and write the result to the log file. 145 if isinstance(self.file, bool) and (force or config.logDebugToFile): 146 self.createFile() 147 148 if force or config.logDebugToFile: 149 if newline: self.file.write(message + '\n') 150 else: self.file.write(message + ' ') 151 self.file.flush() 152 153 if self.stdOut and config.logDebugToStdOut: 154 if newline: print message 155 else: print message,
156
157 -class ResultsLogger(Logger):
158 """ 159 Writes entries into the Dogtail log 160 """
161 - def __init__(self, stdOut = True):
162 Logger.__init__(self, 'results', file = True, stdOut = stdOut)
163 164 # Writes the result of a test case comparison to the log
165 - def log(self, entry):
166 """ 167 Writes the log entry. Requires a 1 {key: value} pair dict for an argument or else it will throw an exception. 168 """ 169 # We require a 1 key: value dict 170 # Strip all leading and trailing witespace from entry dict and convert 171 # to string for writing 172 173 if len(entry) == 1: 174 key = entry.keys() 175 value = entry.values() 176 key = key[0] 177 value = value[0] 178 entry = str(key) + ": " + str(value) 179 else: 180 raise ValueError, entry 181 print "Method argument requires a 1 {key: value} dict. Supplied argument not one {key: value}" 182 183 Logger.log(self, self.stamper.entryStamp() + " " + entry, force = True)
184 185 debugLogger = Logger('debug', config.logDebugToFile) 186 187 import traceback
188 -def exceptionHook(exc, value, tb):
189 tbStringList = traceback.format_exception(exc, value, tb) 190 tbString = ''.join(tbStringList) 191 debugLogger.log(tbString) 192 sys.exc_clear()
193 194 sys.excepthook = exceptionHook 195