~ubuntu-branches/ubuntu/utopic/dogtail/utopic

« back to all changes in this revision

Viewing changes to dogtail/logging.py

  • Committer: Bazaar Package Importer
  • Author(s): Daniel Holbach
  • Date: 2006-12-21 13:33:47 UTC
  • mfrom: (1.2.1 upstream)
  • mto: This revision was merged to the branch mainline in revision 5.
  • Revision ID: james.westby@ubuntu.com-20061221133347-xo9jg11afp5plcka
Tags: upstream-0.6.1
ImportĀ upstreamĀ versionĀ 0.6.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
"""
7
7
 
8
8
__author__ = """Ed Rousseau <rousseau@redhat.com>,
9
 
Zack Cerza <zcerza@redhat.com, 
 
9
Zack Cerza <zcerza@redhat.com,
10
10
David Malcolm <dmalcolm@redhat.com>
11
11
"""
12
12
import os
 
13
import sys
13
14
import time
14
15
import datetime
15
16
from config import config
 
17
import codecs
16
18
 
17
19
# Timestamp class for file logs
18
20
class TimeStamp:
19
 
        """
20
 
        Generates timestamps tempfiles and log entries
21
 
        """
22
 
        def __init__(self):
23
 
                self.now = "0"
24
 
                self.timetup = time.localtime()
25
 
        
26
 
        def zeroPad(self, int, width = 2):
27
 
                """
28
 
                Pads an integer 'int' with zeroes, up to width 'width'.
29
 
                
30
 
                Returns a string.
31
 
                
32
 
                It will not truncate. If you call zeroPad(100, 2), '100' will be returned.
33
 
                """
34
 
                if int < 10 ** width:
35
 
                        return ("0" * (width - len(str(int))) ) + str(int)
36
 
                else: 
37
 
                        return str(int)
38
 
 
39
 
        # file stamper
40
 
        def fileStamp(self, filename, addTime = True):
41
 
                """
42
 
                Generates a filename stamp in the format of filename_YYYYMMDD-hhmmss.
43
 
                A format of filename_YYYYMMDD can be used instead by specifying addTime = False.
44
 
                """
45
 
                self.now = filename.strip() + "_"
46
 
                self.timetup = time.localtime()
47
 
 
48
 
                # Should produce rel-eng style filestamps
49
 
                # format it all pretty by chopping the tuple
50
 
                fieldCount = 3
51
 
                if addTime: fieldCount = fieldCount + 3
52
 
                for i in range(fieldCount):
53
 
                        if i == 3: self.now = self.now + '-'
54
 
                        self.now = self.now + self.zeroPad(self.timetup[i])
55
 
                return self.now
56
 
 
57
 
        # Log entry stamper
58
 
        def entryStamp(self):
59
 
                """
60
 
                Generates a logfile entry stamp of YYYY.MM.DD HH:MM:SS
61
 
                """
62
 
                self.timetup = time.localtime()
63
 
 
64
 
                # This will return a log entry formatted string in YYYY.MM.DD HH:MM:SS
65
 
                for i in range(6):
66
 
                        # put in the year
67
 
                        if i == 0:
68
 
                                self.now = str(self.timetup[i])
69
 
                        # Format Month and Day
70
 
                        elif i == 1 or i == 2:
71
 
                                self.now = self.now + "." + self.zeroPad(self.timetup[i])
72
 
                        else:
73
 
                                x = self.timetup[i]
74
 
                                # make the " " between Day and Hour and put in the hour
75
 
                                if i == 3:
76
 
                                        self.now = self.now + " " + self.zeroPad(self.timetup[i])
77
 
                                # Otherwise Use the ":" divider
78
 
                                else:
79
 
                                        self.now = self.now + ":" + self.zeroPad(self.timetup[i])
80
 
                return self.now
81
 
 
82
 
 
83
 
# Class that writes to the Log
84
 
class LogWriter:
85
 
        """
86
 
        Writes entries into the Dogtail log
87
 
        """
88
 
        def __init__(self):
89
 
                self.entry = {}
90
 
                # Set the logDir - maybe we want to use mktemp(1) for this later.
91
 
                self.logDir = config.logDir #'/tmp/dogtail-' + os.environ['LOGNAME'] + '/'
92
 
                if not os.path.isdir(self.logDir): os.makedirs(self.logDir)
93
 
                self.logfile = ''
94
 
                self.scriptName = config.scriptName 
95
 
                if not self.scriptName: self.scriptName = 'log'
96
 
                self.loghandle = "" # Handle to the logfile
97
 
                self.stamper = TimeStamp()
98
 
                # check to see if we can write to the logDir
99
 
                if os.path.isdir(self.logDir):
100
 
                        # generate a logfile name and check if it already exists
101
 
                        self.logfile = self.logDir + self.stamper.fileStamp(self.scriptName)
102
 
                        i = 0
103
 
                        while os.path.exists(self.logfile):
104
 
                                # Append the pathname
105
 
                                if i == 0:
106
 
                                        self.logfile = self.logfile + "." + str(i)
107
 
                                else:
108
 
                                        logsplit = self.logfile.split(".")
109
 
                                        logsplit[-1] = str(i)
110
 
                                        self.logfile = ".".join(logsplit)
111
 
                                i += 1
112
 
                else:
113
 
                        # If path doesn't exist, raise an exception
114
 
                        raise IOError, "Log path %s does not exist or is not a directory" % self.logDir
115
 
 
116
 
                # Try to create the file and write the header info
117
 
                try:
118
 
                        print "Creating logfile at %s ..." % self.logfile
119
 
                        date = datetime.datetime.strftime(datetime.datetime.now(), '%d %b %Y %H:%M:%S')
120
 
                        self.loghandle = open(self.logfile, 'w')
121
 
                        self.loghandle.write("##### " + self.scriptName + " Created on: " + date + "\n")
122
 
                        self.loghandle.flush()
123
 
                        self.loghandle.close()
124
 
                except IOError:
125
 
                        print "Could not create and write to " + self.logfile
126
 
 
127
 
 
128
 
        # Writes the result of a test case comparison to the log
129
 
        def writeResult(self, entry):
130
 
                """
131
 
                Writes the log entry. Requires a 1 {key: value} pair dict for an argument or else it will throw an exception.
132
 
                """
133
 
                self.entry = entry
134
 
                # We require a 1 key: value dict
135
 
                # Strip all leading and trailing witespace from entry dict and convert
136
 
        # to string for writing
137
 
 
138
 
                if len(self.entry) == 1:
139
 
                        key = self.entry.keys()
140
 
                        value = self.entry.values()
141
 
                        key = key[0]
142
 
                        value = value[0]
143
 
                        self.entry = str(key) + ":      " + str(value)
144
 
                else:
145
 
                        raise ValueError
146
 
                        print "Method argument requires a 1 {key: value} dict. Supplied argument not one {key: value}"
147
 
 
148
 
                # Try to open and write the result to the log
149
 
                try:
150
 
                        self.loghandle = open(self.logfile, 'a')
151
 
                        self.loghandle.write(self.stamper.entryStamp() + "      " + self.entry + "\n")
152
 
                        self.loghandle.flush()
153
 
                        self.loghandle.close()
154
 
 
155
 
                except IOError:
156
 
                        print "Could not write to file " + self.logfile
 
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
157
83
 
158
84
class IconLogger:
159
 
        """
160
 
        Writes entries to the tooltip of an icon in the notification area or the desktop.
161
 
        """
162
 
        trayicon = None
163
 
        def __init__(self, config = None, module_list = None):
164
 
                if not IconLogger.trayicon:
165
 
                        from trayicon import TrayIcon
166
 
                        IconLogger.trayicon = TrayIcon()
167
 
                        if IconLogger.trayicon.proc: self.works = True
168
 
                        else: self.works = False
169
 
                        iconName = 'dogtail-tail-48.png'
170
 
                        iconPath = '/usr/share/icons/hicolor/48x48/apps/' + iconName
171
 
                        if os.path.exists(iconPath):
172
 
                                IconLogger.trayicon.set_icon(iconPath)
173
 
                        self.message('dogtail running...')
174
 
 
175
 
        def message(self, msg):
176
 
                """
177
 
                Display a message to the user
178
 
                """
179
 
                IconLogger.trayicon.set_tooltip(msg)
180
 
 
181
 
class DebugLogger:
182
 
        """
183
 
        Writes entries to standard out, and to an IconLogger if possible.
184
 
        """
185
 
        def __init__(self):
186
 
                self.iconLogger = IconLogger()
187
 
 
188
 
        def log(self, message):
189
 
                """
190
 
                Hook used for logging messages. Might eventually be a virtual
191
 
                function, but nice and simple for now.
192
 
                """
193
 
                # Try to use the IconLogger.
194
 
                if self.iconLogger.works: self.iconLogger.message(message)
195
 
                # Also write to standard out.
196
 
                print message
197
 
 
198
 
debugLogger = DebugLogger()
 
85
    """
 
86
    Writes entries to the tooltip of an icon in the notification area or the desktop.
 
87
    """
 
88
    trayicon = None
 
89
    def __init__(self):
 
90
        if not IconLogger.trayicon:
 
91
            from trayicon import TrayIcon
 
92
            IconLogger.trayicon = TrayIcon()
 
93
            if IconLogger.trayicon.proc: self.works = True
 
94
            else: self.works = False
 
95
            iconName = 'dogtail-tail-48.png'
 
96
            iconPath = '/usr/share/icons/hicolor/48x48/apps/' + iconName
 
97
            if os.path.exists(iconPath):
 
98
                IconLogger.trayicon.set_icon(iconPath)
 
99
            self.message('dogtail running...')
 
100
 
 
101
    def message(self, msg):
 
102
        """
 
103
        Display a message to the user
 
104
        """
 
105
        IconLogger.trayicon.set_tooltip(msg)
 
106
 
 
107
    def __del__(self):
 
108
        IconLogger.trayicon.close()
 
109
 
 
110
class Logger:
 
111
    """
 
112
    Writes entries to standard out, and to an IconLogger if desired.
 
113
    """
 
114
    iconLogger = None
 
115
    stamper = TimeStamp()
 
116
    def __init__(self, logName, file = False, stdOut = True):
 
117
        """
 
118
        FIXME! make this log to a file based on the name arg.
 
119
 
 
120
        name: the name of the log
 
121
 
 
122
        file: The file object to log to.
 
123
 
 
124
        stdOut: Whether to log to standard out.
 
125
        """
 
126
        self.logName = logName
 
127
        self.stdOut = stdOut
 
128
        self.file = file # Handle to the logfile
 
129
        if not self.file: return
 
130
 
 
131
        logDir = config.logDir
 
132
        if not os.path.isdir(logDir): os.makedirs(logDir)
 
133
 
 
134
        scriptName = config.scriptName
 
135
        if not scriptName: scriptName = 'log'
 
136
        self.fileName = scriptName
 
137
 
 
138
        # check to see if we can write to the logDir
 
139
        if os.path.isdir(logDir):
 
140
            # generate a logfile name and check if it already exists
 
141
            self.fileName = logDir + self.stamper.fileStamp(self.fileName) + '_' + self.logName
 
142
            i = 0
 
143
            while os.path.exists(self.fileName):
 
144
                # Append the pathname
 
145
                if i == 0:
 
146
                    self.fileName = self.fileName + "." + str(i)
 
147
                else:
 
148
                    logsplit = self.fileName.split(".")
 
149
                    logsplit[-1] = str(i)
 
150
                    self.fileName = ".".join(logsplit)
 
151
                i += 1
 
152
        else:
 
153
            # If path doesn't exist, raise an exception
 
154
            raise IOError, "Log path %s does not exist or is not a directory" % logDir
 
155
 
 
156
        # Try to create the file and write the header info
 
157
        try:
 
158
            print "Creating logfile at %s ..." % self.fileName
 
159
            self.file = codecs.open(self.fileName, mode = 'wb', encoding = 'utf-8')
 
160
            self.file.write("##### " + os.path.basename(self.fileName) + '\n')
 
161
            self.file.flush()
 
162
            #self.file.close()
 
163
        except IOError:
 
164
            print "Could not create and write to " + self.fileName
 
165
 
 
166
    def log(self, message):
 
167
        """
 
168
        Hook used for logging messages. Might eventually be a virtual
 
169
        function, but nice and simple for now.
 
170
        """
 
171
        message = message.decode('utf-8', 'replace')
 
172
 
 
173
        # Try to use the IconLogger.
 
174
        if self.iconLogger and self.iconLogger.works:
 
175
            self.iconLogger.message(message)
 
176
        
 
177
        # Also write to standard out.
 
178
        if self.stdOut: print message
 
179
 
 
180
        # Try to open and write the result to the log file.
 
181
        if not self.file: return
 
182
        try:
 
183
            #self.file = open(self.fileName, 'a')
 
184
            self.file.write(message + '\n')
 
185
            self.file.flush()
 
186
            #self.file.close()
 
187
        except IOError:
 
188
            print "Could not write to file " + self.fileName
 
189
 
 
190
class ResultsLogger(Logger):
 
191
    """
 
192
    Writes entries into the Dogtail log
 
193
    """
 
194
    def __init__(self, stdOut = True):
 
195
        Logger.__init__(self, 'results', file = True, stdOut = stdOut)
 
196
        # Set the logDir - maybe we want to use mktemp(1) for this later.
 
197
 
 
198
    # Writes the result of a test case comparison to the log
 
199
    def log(self, entry):
 
200
        """
 
201
        Writes the log entry. Requires a 1 {key: value} pair dict for an argument or else it will throw an exception.
 
202
        """
 
203
        # We require a 1 key: value dict
 
204
        # Strip all leading and trailing witespace from entry dict and convert
 
205
    # to string for writing
 
206
 
 
207
        if len(entry) == 1:
 
208
            key = entry.keys()
 
209
            value = entry.values()
 
210
            key = key[0]
 
211
            value = value[0]
 
212
            entry = str(key) + ":      " + str(value)
 
213
        else:
 
214
            raise ValueError, entry
 
215
            print "Method argument requires a 1 {key: value} dict. Supplied argument not one {key: value}"
 
216
 
 
217
        Logger.log(self, self.stamper.entryStamp() + "      " + entry)
 
218
 
 
219
debugLogger = Logger('debug', file = True)
 
220
 
 
221
import traceback
 
222
def exceptionHook(exc, value, tb):
 
223
    tbStringList = traceback.format_exception(exc, value, tb)
 
224
    tbString = ''.join(tbStringList)
 
225
    debugLogger.log(tbString)
 
226
    sys.exc_clear()
 
227
 
 
228
sys.excepthook = exceptionHook