~certify-web-dev/twisted/certify-trunk

« back to all changes in this revision

Viewing changes to twisted/python/log.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2007-01-17 14:52:35 UTC
  • mto: (2.2.3 sid)
  • mto: This revision was merged to the branch mainline in revision 15.
  • Revision ID: james.westby@ubuntu.com-20070117145235-7gaj253qxi5wiq16
Tags: upstream-2.5.0
ImportĀ upstreamĀ versionĀ 2.5.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
2
2
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
3
3
# See LICENSE for details.
4
4
 
5
 
 
6
5
"""Logging and metrics infrastructure.
7
6
"""
8
7
 
 
8
from __future__ import division
 
9
 
9
10
# System Imports
10
11
import sys
11
12
import time
12
13
import warnings
 
14
import datetime
13
15
 
14
16
# Sibling Imports
15
17
from twisted.python import util, context, reflect
16
18
 
17
 
# Backwards compat
18
 
try:
19
 
    UnicodeEncodeError # Introduced sometime after Python 2.2.3
20
 
except NameError:
21
 
    UnicodeEncodeError = UnicodeError
22
 
 
23
 
 
24
19
class ILogContext:
25
20
    """Actually, this interface is just a synoym for the dictionary interface,
26
21
    but it serves as a key for the default information in a log.
56
51
    except:
57
52
        err(system=lp)
58
53
 
59
 
def write(stuff):
60
 
    """Write some data to the log.
61
 
    DEPRECATED. Use L{msg} instead."""
62
 
    warnings.warn("Use log.msg, not log.write.", DeprecationWarning, stacklevel=2)
63
 
    msg(str(stuff))
64
 
 
65
 
def debug(*stuff,**otherstuff):
66
 
    """
67
 
    Write some debug data to the log. It passes debug=1 in the log
68
 
    dict.
69
 
 
70
 
    DEPRECATED (Since Twisted 2.1): Pass debug=1 to msg() yourself.
71
 
    """
72
 
    warnings.warn("Use log.msg(..., debug=True), not log.debug().", DeprecationWarning, stacklevel=2)
73
 
    msg(debug=1, *stuff, **otherstuff)
74
 
 
75
54
def showwarning(message, category, filename, lineno, file=None):
76
55
    if file is None:
77
 
        msg(warning=message, category=category, filename=filename, lineno=lineno,
 
56
        msg(warning=message, category=reflect.qual(category), filename=filename, lineno=lineno,
78
57
            format="%(filename)s:%(lineno)s: %(category)s: %(warning)s")
79
58
    else:
80
59
        _oldshowwarning(message, category, filename, lineno, file)
84
63
_ignoreErrors = []
85
64
 
86
65
def startKeepingErrors():
87
 
    """Support function for testing frameworks.
 
66
    """
 
67
    DEPRECATED in Twisted 2.5.
 
68
    
 
69
    Support function for testing frameworks.
88
70
 
89
71
    Start keeping errors in a buffer which can be retrieved (and emptied) with
90
72
    flushErrors.
91
73
    """
 
74
    warnings.warn("log.startKeepingErrors is deprecated since Twisted 2.5",
 
75
                  category=DeprecationWarning, stacklevel=2)
92
76
    global _keepErrors
93
77
    _keepErrors = 1
94
78
 
95
79
 
96
80
def flushErrors(*errorTypes):
97
 
    """Support function for testing frameworks.
 
81
    """
 
82
    DEPRECATED in Twisted 2.5.  See L{TestCase.flushLoggedErrors}.
 
83
 
 
84
    Support function for testing frameworks.
98
85
 
99
86
    Return a list of errors that occurred since the last call to flushErrors().
100
87
    (This will return None unless startKeepingErrors has been called.)
101
88
    """
102
89
 
 
90
    warnings.warn("log.flushErrors is deprecated since Twisted 2.5. "
 
91
                  "If you need to flush errors from within a unittest, "
 
92
                  "use TestCase.flushLoggedErrors instead.",
 
93
                  category=DeprecationWarning, stacklevel=2)
 
94
    return _flushErrors(*errorTypes)
 
95
 
 
96
 
 
97
def _flushErrors(*errorTypes):
 
98
    """
 
99
    PRIVATE. DEPRECATED. DON'T USE.
 
100
    """
103
101
    global _keptErrors
104
102
    k = _keptErrors
105
103
    _keptErrors = []
114
112
    return k
115
113
 
116
114
def ignoreErrors(*types):
 
115
    """DEPRECATED"""
 
116
    warnings.warn("log.ignoreErrors is deprecated since Twisted 2.5",
 
117
                  category=DeprecationWarning, stacklevel=2)
 
118
    _ignore(*types)
 
119
 
 
120
def _ignore(*types):
 
121
    """
 
122
    PRIVATE. DEPRECATED. DON'T USE.
 
123
    """
117
124
    for type in types:
118
125
        _ignoreErrors.append(type)
119
126
 
120
127
def clearIgnores():
 
128
    """DEPRECATED"""
 
129
    warnings.warn("log.clearIgnores is deprecated since Twisted 2.5",
 
130
                  category=DeprecationWarning, stacklevel=2)
 
131
    _clearIgnores()
 
132
 
 
133
def _clearIgnores():
 
134
    """
 
135
    PRIVATE. DEPRECATED. DON'T USE.
 
136
    """
121
137
    global _ignoreErrors
122
138
    _ignoreErrors = []
123
139
 
124
 
def err(_stuff=None,**kw):
 
140
 
 
141
def err(_stuff=None, _why=None, **kw):
125
142
    """
126
143
    Write a failure to the log.
127
144
    """
142
159
                    _keptErrors.append(_stuff)
143
160
            else:
144
161
                _keptErrors.append(_stuff)
145
 
        msg(failure=_stuff, isError=1, **kw)
 
162
        msg(failure=_stuff, why=_why, isError=1, **kw)
146
163
    elif isinstance(_stuff, Exception):
147
 
        msg(failure=failure.Failure(_stuff), isError=1, **kw)
 
164
        msg(failure=failure.Failure(_stuff), why=_why, isError=1, **kw)
148
165
    else:
149
 
        msg(repr(_stuff), isError=1, **kw)
 
166
        msg(repr(_stuff), why=_why, isError=1, **kw)
150
167
 
151
168
deferr = err
152
169
 
162
179
        """
163
180
        return '-'
164
181
 
165
 
 
166
 
class EscapeFromTheMeaninglessConfinesOfCapital:
167
 
    def own(self, owner):
168
 
        warnings.warn("Foolish capitalist!  Your opulent toilet will be your undoing!!",
169
 
                      DeprecationWarning, stacklevel=2)
170
 
    def disown(self, owner):
171
 
        warnings.warn("The proletariat is victorious.",
172
 
                      DeprecationWarning, stacklevel=2)
173
 
 
174
 
logOwner = EscapeFromTheMeaninglessConfinesOfCapital()
175
 
 
176
 
 
177
182
class LogPublisher:
178
183
    """Class for singleton log message publishing."""
179
184
 
224
229
                raise
225
230
            except:
226
231
                o = self.observers.pop(i)
227
 
                msg("Log observer %s failed, removing from observer list." % (o,))
228
 
                err()
 
232
                err(failure.Failure(),
 
233
                    "Log observer %s failed, removing from observer list." % (o,))
229
234
 
230
235
 
231
236
try:
238
243
 
239
244
 
240
245
class FileLogObserver:
241
 
    """Log observer that writes to a file-like object.
 
246
    """
 
247
    Log observer that writes to a file-like object.
242
248
 
243
 
    @ivar timeFormat: Format string passed to strftime()
 
249
    @type timeFormat: C{str} or C{NoneType}
 
250
    @ivar timeFormat: If not C{None}, the format string passed to strftime().
244
251
    """
245
 
    timeFormat = "%Y/%m/%d %H:%M %Z"
 
252
    timeFormat = None
246
253
 
247
254
    def __init__(self, f):
248
255
        self.write = f.write
269
276
                    text = 'PATHOLOGICAL ERROR IN BOTH FORMAT STRING AND MESSAGE DETAILS, MESSAGE LOST'
270
277
        return text
271
278
 
 
279
 
 
280
    def getTimezoneOffset(self):
 
281
        """
 
282
        Return the current local timezone offset from UTC.
 
283
 
 
284
        @rtype: C{int}
 
285
        @return: The number of seconds offset from UTC.  West is positive,
 
286
        east is negative.
 
287
        """
 
288
        if time.daylight:
 
289
            return time.altzone
 
290
        return time.timezone
 
291
 
 
292
 
 
293
    def formatTime(self, when):
 
294
        """
 
295
        Return the given UTC value formatted as a human-readable string
 
296
        representing that time in the local timezone.
 
297
 
 
298
        @type when: C{int}
 
299
        @param when: POSIX timestamp to convert to a human-readable string.
 
300
 
 
301
        @rtype: C{str}
 
302
        """
 
303
        if self.timeFormat is not None:
 
304
            return time.strftime(self.timeFormat, time.localtime(when))
 
305
 
 
306
        tzOffset = -self.getTimezoneOffset()
 
307
        when = datetime.datetime.utcfromtimestamp(when + tzOffset)
 
308
        tzHour = int(tzOffset / 60 / 60)
 
309
        tzMin = int(tzOffset / 60 % 60)
 
310
        return '%d/%02d/%02d %02d:%02d %+03d%02d' % (
 
311
            when.year, when.month, when.day,
 
312
            when.hour, when.minute,
 
313
            tzHour, tzMin)
 
314
 
 
315
 
272
316
    def emit(self, eventDict):
273
317
        edm = eventDict['message']
274
318
        if not edm:
275
319
            if eventDict['isError'] and eventDict.has_key('failure'):
276
 
                text = eventDict['failure'].getTraceback()
 
320
                text = ((eventDict.get('why') or 'Unhandled Error')
 
321
                        + '\n' + eventDict['failure'].getTraceback())
277
322
            elif eventDict.has_key('format'):
278
323
                text = self._safeFormat(eventDict['format'], eventDict)
279
324
            else:
282
327
        else:
283
328
            text = ' '.join(map(reflect.safe_str, edm))
284
329
 
285
 
        timeStr = time.strftime(self.timeFormat, time.localtime(eventDict['time']))
 
330
        timeStr = self.formatTime(eventDict['time'])
286
331
        fmtDict = {'system': eventDict['system'], 'text': text.replace("\n", "\n\t")}
287
332
        msgStr = self._safeFormat("[%(system)s] %(text)s\n", fmtDict)
288
333