~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/trace.py

Merge

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, Canonical Ltd
2
 
 
3
 
"""Messages and logging for bazaar-ng.
4
 
 
5
 
Messages are supplied by callers as a string-formatting template, plus values
6
 
to be inserted into it.  The actual %-formatting is deferred to the log
7
 
library so that it doesn't need to be done for messages that won't be emitted.
8
 
 
9
 
Messages are classified by severity levels: critical, error, warning, info,
10
 
and debug.
11
 
 
12
 
They can be sent to two places: to stderr, and to ~/.bzr.log.  For purposes
13
 
such as running the test suite, they can also be redirected away from both of
14
 
those two places to another location.
15
 
 
16
 
~/.bzr.log gets all messages, and full tracebacks for uncaught exceptions.
17
 
This trace file is always in UTF-8, regardless of the user's default encoding,
18
 
so that we can always rely on writing any message.
19
 
 
20
 
Output to stderr depends on the mode chosen by the user.  By default, messages
21
 
of info and above are sent out, which results in progress messages such as the
22
 
list of files processed by add and commit.  In quiet mode, only warnings and
23
 
above are shown.  In debug mode, stderr gets debug messages too.
24
 
 
25
 
Errors that terminate an operation are generally passed back as exceptions;
26
 
others may be just emitted as messages.
27
 
 
28
 
Exceptions are reported in a brief form to stderr so as not to look scary.
29
 
BzrErrors are required to be able to format themselves into a properly
30
 
explanatory message.  This is not true for builtin excexceptions such as
31
 
KeyError, which typically just str to "0".  They're printed in a different
32
 
form.
33
 
"""
34
 
 
35
 
# TODO: in debug mode, stderr should get full tracebacks and also
36
 
# debug messages.  (Is this really needed?)
37
 
 
38
 
# FIXME: Unfortunately it turns out that python's logging module
39
 
# is quite expensive, even when the message is not printed by any handlers.
40
 
# We should perhaps change back to just simply doing it here.
41
 
 
42
 
 
43
 
import sys
44
 
import os
45
 
import logging
46
 
 
47
 
import bzrlib
48
 
from bzrlib.errors import BzrError, BzrNewError
49
 
 
50
 
 
51
 
_file_handler = None
52
 
_stderr_handler = None
53
 
_stderr_quiet = False
54
 
_trace_file = None
55
 
_bzr_log_file = None
56
 
 
57
 
 
58
 
class QuietFormatter(logging.Formatter):
59
 
    """Formatter that supresses the details of errors.
60
 
 
61
 
    This is used by default on stderr so as not to scare the user.
62
 
    """
63
 
    # At first I tried overriding formatException to suppress the
64
 
    # exception details, but that has global effect: no loggers
65
 
    # can get the exception details is we suppress them here.
66
 
 
67
 
    def format(self, record):
68
 
        if record.levelno >= logging.WARNING:
69
 
            s = 'bzr: ' + record.levelname + ': '
70
 
        else:
71
 
            s = ''
72
 
        s += record.getMessage()
73
 
        if record.exc_info:
74
 
            s += '\n' + format_exception_short(record.exc_info)
75
 
        return s
76
 
        
77
 
# configure convenient aliases for output routines
78
 
 
79
 
_bzr_logger = logging.getLogger('bzr')
80
 
 
81
 
def note(*args, **kwargs):
82
 
    import bzrlib.ui
83
 
    bzrlib.ui.ui_factory.clear_term()
84
 
    _bzr_logger.info(*args, **kwargs)
85
 
 
86
 
def warning(*args, **kwargs):
87
 
    import bzrlib.ui
88
 
    bzrlib.ui.ui_factory.clear_term()
89
 
    _bzr_logger.warning(*args, **kwargs)
90
 
 
91
 
info = note
92
 
log_error = _bzr_logger.error
93
 
error =     _bzr_logger.error
94
 
 
95
 
 
96
 
def mutter(fmt, *args):
97
 
    if _trace_file is None:
98
 
        return
99
 
    if hasattr(_trace_file, 'closed') and _trace_file.closed:
100
 
        return
101
 
    if len(args) > 0:
102
 
        out = fmt % args
103
 
    else:
104
 
        out = fmt
105
 
    out += '\n'
106
 
    _trace_file.write(out)
107
 
debug = mutter
108
 
 
109
 
 
110
 
def _rollover_trace_maybe(trace_fname):
111
 
    import stat
112
 
    try:
113
 
        size = os.stat(trace_fname)[stat.ST_SIZE]
114
 
        if size <= 4 << 20:
115
 
            return
116
 
        old_fname = trace_fname + '.old'
117
 
        from osutils import rename
118
 
        rename(trace_fname, old_fname)
119
 
    except OSError:
120
 
        return
121
 
 
122
 
 
123
 
def open_tracefile(tracefilename='~/.bzr.log'):
124
 
    # Messages are always written to here, so that we have some
125
 
    # information if something goes wrong.  In a future version this
126
 
    # file will be removed on successful completion.
127
 
    global _file_handler, _bzr_log_file
128
 
    import stat, codecs
129
 
 
130
 
    trace_fname = os.path.join(os.path.expanduser(tracefilename))
131
 
    _rollover_trace_maybe(trace_fname)
132
 
    try:
133
 
        LINE_BUFFERED = 1
134
 
        tf = codecs.open(trace_fname, 'at', 'utf8', buffering=LINE_BUFFERED)
135
 
        _bzr_log_file = tf
136
 
        if tf.tell() == 0:
137
 
            tf.write("\nthis is a debug log for diagnosing/reporting problems in bzr\n")
138
 
            tf.write("you can delete or truncate this file, or include sections in\n")
139
 
            tf.write("bug reports to bazaar-ng@lists.canonical.com\n\n")
140
 
        _file_handler = logging.StreamHandler(tf)
141
 
        fmt = r'[%(process)5d] %(asctime)s.%(msecs)03d %(levelname)s: %(message)s'
142
 
        datefmt = r'%a %H:%M:%S'
143
 
        _file_handler.setFormatter(logging.Formatter(fmt, datefmt))
144
 
        _file_handler.setLevel(logging.DEBUG)
145
 
        logging.getLogger('').addHandler(_file_handler)
146
 
    except IOError, e:
147
 
        warning("failed to open trace file: %s" % (e))
148
 
 
149
 
 
150
 
def log_startup(argv):
151
 
    debug('\n\nbzr %s invoked on python %s (%s)',
152
 
          bzrlib.__version__,
153
 
          '.'.join(map(str, sys.version_info)),
154
 
          sys.platform)
155
 
    debug('  arguments: %r', argv)
156
 
    debug('  working dir: %r', os.getcwdu())
157
 
 
158
 
 
159
 
def log_exception(msg=None):
160
 
    """Log the last exception to stderr and the trace file.
161
 
 
162
 
    The exception string representation is used as the error
163
 
    summary, unless msg is given.
164
 
    """
165
 
    if msg:
166
 
        error(msg)
167
 
    else:
168
 
        exc_str = format_exception_short(sys.exc_info())
169
 
        error(exc_str)
170
 
    log_exception_quietly()
171
 
 
172
 
 
173
 
def log_exception_quietly():
174
 
    """Log the last exception to the trace file only.
175
 
 
176
 
    Used for exceptions that occur internally and that may be 
177
 
    interesting to developers but not to users.  For example, 
178
 
    errors loading plugins.
179
 
    """
180
 
    import traceback
181
 
    debug(traceback.format_exc())
182
 
 
183
 
 
184
 
def enable_default_logging():
185
 
    """Configure default logging to stderr and .bzr.log"""
186
 
    # FIXME: if this is run twice, things get confused
187
 
    global _stderr_handler, _file_handler, _trace_file, _bzr_log_file
188
 
    _stderr_handler = logging.StreamHandler()
189
 
    _stderr_handler.setFormatter(QuietFormatter())
190
 
    logging.getLogger('').addHandler(_stderr_handler)
191
 
    _stderr_handler.setLevel(logging.INFO)
192
 
    if not _file_handler:
193
 
        open_tracefile()
194
 
    _trace_file = _bzr_log_file
195
 
    if _file_handler:
196
 
        _file_handler.setLevel(logging.DEBUG)
197
 
    _bzr_logger.setLevel(logging.DEBUG) 
198
 
 
199
 
 
200
 
 
201
 
def be_quiet(quiet=True):
202
 
    global _stderr_handler, _stderr_quiet
203
 
    
204
 
    _stderr_quiet = quiet
205
 
    if quiet:
206
 
        _stderr_handler.setLevel(logging.WARNING)
207
 
    else:
208
 
        _stderr_handler.setLevel(logging.INFO)
209
 
 
210
 
 
211
 
def is_quiet():
212
 
    global _stderr_quiet
213
 
    return _stderr_quiet
214
 
 
215
 
 
216
 
def disable_default_logging():
217
 
    """Turn off default log handlers.
218
 
 
219
 
    This is intended to be used by the test framework, which doesn't
220
 
    want leakage from the code-under-test into the main logs.
221
 
    """
222
 
 
223
 
    l = logging.getLogger('')
224
 
    l.removeHandler(_stderr_handler)
225
 
    if _file_handler:
226
 
        l.removeHandler(_file_handler)
227
 
    _trace_file = None
228
 
 
229
 
 
230
 
def enable_test_log(to_file):
231
 
    """Redirect logging to a temporary file for a test
232
 
    
233
 
    returns an opaque reference that should be passed to disable_test_log
234
 
    after the test complete.
235
 
    """
236
 
    disable_default_logging()
237
 
    global _trace_file
238
 
    hdlr = logging.StreamHandler(to_file)
239
 
    hdlr.setLevel(logging.DEBUG)
240
 
    hdlr.setFormatter(logging.Formatter('%(levelname)8s  %(message)s'))
241
 
    _bzr_logger.addHandler(hdlr)
242
 
    _bzr_logger.setLevel(logging.DEBUG)
243
 
    result = hdlr, _trace_file
244
 
    _trace_file = to_file
245
 
    return result
246
 
 
247
 
 
248
 
def disable_test_log((test_log_hdlr, old_trace_file)):
249
 
    _bzr_logger.removeHandler(test_log_hdlr)
250
 
    test_log_hdlr.close()
251
 
    _trace_file = old_trace_file
252
 
    enable_default_logging()
253
 
 
254
 
 
255
 
def format_exception_short(exc_info):
256
 
    """Make a short string form of an exception.
257
 
 
258
 
    This is used for display to stderr.  It specially handles exception
259
 
    classes without useful string methods.
260
 
 
261
 
    The result has no trailing newline.
262
 
 
263
 
    exc_info - typically an exception from sys.exc_info()
264
 
    """
265
 
    exc_type, exc_object, exc_tb = exc_info
266
 
    try:
267
 
        if exc_type is None:
268
 
            return '(no exception)'
269
 
        if isinstance(exc_object, (BzrError, BzrNewError)):
270
 
            return str(exc_object)
271
 
        else:
272
 
            import traceback
273
 
            tb = traceback.extract_tb(exc_tb)
274
 
            msg = '%s: %s' % (exc_type, exc_object)
275
 
            if msg[-1] == '\n':
276
 
                msg = msg[:-1]
277
 
            if tb:
278
 
                msg += '\n  at %s line %d\n  in %s' % (tb[-1][:3])
279
 
            return msg
280
 
    except Exception, formatting_exc:
281
 
        # XXX: is this really better than just letting it run up?
282
 
        return '(error formatting exception of type %s: %s)' \
283
 
                % (exc_type, formatting_exc)