~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/trace.py

  • Committer: Martin Packman
  • Date: 2011-12-13 17:10:47 UTC
  • mto: This revision was merged to the branch mainline in revision 6367.
  • Revision ID: martin.packman@canonical.com-20111213171047-esvi1kyfbuehmhrm
Minor tweaks including normalising _fs_enc value

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
"""Messages and logging for bazaar-ng.
 
17
"""Messages and logging.
18
18
 
19
19
Messages are supplied by callers as a string-formatting template, plus values
20
20
to be inserted into it.  The actual %-formatting is deferred to the log
33
33
 
34
34
Output to stderr depends on the mode chosen by the user.  By default, messages
35
35
of info and above are sent out, which results in progress messages such as the
36
 
list of files processed by add and commit.  In quiet mode, only warnings and
37
 
above are shown.  In debug mode, stderr gets debug messages too.
 
36
list of files processed by add and commit.  In debug mode, stderr gets debug messages too.
38
37
 
39
38
Errors that terminate an operation are generally passed back as exceptions;
40
39
others may be just emitted as messages.
49
48
# FIXME: Unfortunately it turns out that python's logging module
50
49
# is quite expensive, even when the message is not printed by any handlers.
51
50
# We should perhaps change back to just simply doing it here.
 
51
#
 
52
# On the other hand, as of 1.2 we generally only call the mutter() statement
 
53
# if (according to debug_flags) we actually intend to write it.  So the
 
54
# increased cost of logging.py is not so bad, and we could standardize on
 
55
# that.
52
56
 
 
57
import logging
53
58
import os
54
59
import sys
55
 
import re
 
60
import time
56
61
 
57
62
from bzrlib.lazy_import import lazy_import
58
63
lazy_import(globals(), """
 
64
from cStringIO import StringIO
59
65
import errno
60
 
import logging
 
66
import locale
 
67
import tempfile
 
68
import traceback
61
69
""")
62
70
 
63
71
import bzrlib
64
 
from bzrlib.symbol_versioning import (deprecated_function,
65
 
        zero_nine,
66
 
        )
67
72
 
68
73
lazy_import(globals(), """
69
 
from bzrlib import debug
 
74
from bzrlib import (
 
75
    debug,
 
76
    errors,
 
77
    osutils,
 
78
    ui,
 
79
    )
70
80
""")
71
81
 
72
 
_file_handler = None
73
 
_stderr_handler = None
74
 
_stderr_quiet = False
 
82
 
 
83
# global verbosity for bzrlib; controls the log level for stderr; 0=normal; <0
 
84
# is quiet; >0 is verbose.
 
85
_verbosity_level = 0
 
86
 
 
87
# File-like object where mutter/debug output is currently sent.  Can be
 
88
# changed by _push_log_file etc.  This is directly manipulated by some
 
89
# external code; maybe there should be functions to do that more precisely
 
90
# than push/pop_log_file.
75
91
_trace_file = None
76
 
_trace_depth = 0
77
 
_bzr_log_file = None
78
 
 
79
 
 
80
 
# configure convenient aliases for output routines
81
 
 
 
92
 
 
93
# Absolute path for ~/.bzr.log.  Not changed even if the log/trace output is
 
94
# redirected elsewhere.  Used to show the location in --version.
 
95
_bzr_log_filename = None
 
96
 
 
97
# The time the first message was written to the trace file, so that we can
 
98
# show relative times since startup.
 
99
_bzr_log_start_time = bzrlib._start_time
 
100
 
 
101
 
 
102
# held in a global for quick reference
82
103
_bzr_logger = logging.getLogger('bzr')
83
104
 
 
105
 
84
106
def note(*args, **kwargs):
85
 
    # FIXME note always emits utf-8, regardless of the terminal encoding
86
 
    import bzrlib.ui
87
 
    bzrlib.ui.ui_factory.clear_term()
 
107
    """Output a note to the user.
 
108
 
 
109
    Takes the same parameters as logging.info.
 
110
 
 
111
    :return: None
 
112
    """
 
113
    # FIXME: clearing the ui and then going through the abstract logging
 
114
    # framework is whack; we should probably have a logging Handler that
 
115
    # deals with terminal output if needed.
 
116
    ui.ui_factory.clear_term()
88
117
    _bzr_logger.info(*args, **kwargs)
89
118
 
 
119
 
90
120
def warning(*args, **kwargs):
91
 
    import bzrlib.ui
92
 
    bzrlib.ui.ui_factory.clear_term()
 
121
    ui.ui_factory.clear_term()
93
122
    _bzr_logger.warning(*args, **kwargs)
94
123
 
95
 
info = note
96
 
log_error = _bzr_logger.error
97
 
error =     _bzr_logger.error
 
124
 
 
125
def show_error(*args, **kwargs):
 
126
    """Show an error message to the user.
 
127
 
 
128
    Don't use this for exceptions, use report_exception instead.
 
129
    """
 
130
    _bzr_logger.error(*args, **kwargs)
98
131
 
99
132
 
100
133
def mutter(fmt, *args):
101
134
    if _trace_file is None:
102
135
        return
 
136
    # XXX: Don't check this every time; instead anyone who closes the file
 
137
    # ought to deregister it.  We can tolerate None.
103
138
    if (getattr(_trace_file, 'closed', None) is not None) and _trace_file.closed:
104
139
        return
105
140
 
118
153
        out = fmt % tuple(real_args)
119
154
    else:
120
155
        out = fmt
121
 
    out += '\n'
 
156
    now = time.time()
 
157
    timestamp = '%0.3f  ' % (now - _bzr_log_start_time,)
 
158
    out = timestamp + out + '\n'
122
159
    _trace_file.write(out)
123
 
    # TODO: jam 20051227 Consider flushing the trace file to help debugging
124
 
    #_trace_file.flush()
 
160
    # there's no explicit flushing; the file is typically line buffered.
 
161
 
 
162
 
 
163
def mutter_callsite(stacklevel, fmt, *args):
 
164
    """Perform a mutter of fmt and args, logging the call trace.
 
165
 
 
166
    :param stacklevel: The number of frames to show. None will show all
 
167
        frames.
 
168
    :param fmt: The format string to pass to mutter.
 
169
    :param args: A list of substitution variables.
 
170
    """
 
171
    outf = StringIO()
 
172
    if stacklevel is None:
 
173
        limit = None
 
174
    else:
 
175
        limit = stacklevel + 1
 
176
    traceback.print_stack(limit=limit, file=outf)
 
177
    formatted_lines = outf.getvalue().splitlines()
 
178
    formatted_stack = '\n'.join(formatted_lines[:-2])
 
179
    mutter(fmt + "\nCalled from:\n%s", *(args + (formatted_stack,)))
125
180
 
126
181
 
127
182
def _rollover_trace_maybe(trace_fname):
131
186
        if size <= 4 << 20:
132
187
            return
133
188
        old_fname = trace_fname + '.old'
134
 
        from osutils import rename
135
 
        rename(trace_fname, old_fname)
 
189
        osutils.rename(trace_fname, old_fname)
136
190
    except OSError:
137
191
        return
138
192
 
139
193
 
140
 
def open_tracefile(tracefilename=None):
141
 
    # Messages are always written to here, so that we have some
142
 
    # information if something goes wrong.  In a future version this
143
 
    # file will be removed on successful completion.
144
 
    global _file_handler, _bzr_log_file
145
 
    import codecs
146
 
 
147
 
    if tracefilename is None:
 
194
def _get_bzr_log_filename():
 
195
    bzr_log = os.environ.get('BZR_LOG')
 
196
    if bzr_log:
 
197
        return bzr_log
 
198
    home = os.environ.get('BZR_HOME')
 
199
    if home is None:
148
200
        if sys.platform == 'win32':
149
201
            from bzrlib import win32utils
150
202
            home = win32utils.get_home_location()
151
203
        else:
152
204
            home = os.path.expanduser('~')
153
 
        tracefilename = os.path.join(home, '.bzr.log')
154
 
 
155
 
    trace_fname = os.path.expanduser(tracefilename)
156
 
    _rollover_trace_maybe(trace_fname)
 
205
    return os.path.join(home, '.bzr.log')
 
206
 
 
207
 
 
208
def _open_bzr_log():
 
209
    """Open the .bzr.log trace file.
 
210
 
 
211
    If the log is more than a particular length, the old file is renamed to
 
212
    .bzr.log.old and a new file is started.  Otherwise, we append to the
 
213
    existing file.
 
214
 
 
215
    This sets the global _bzr_log_filename.
 
216
    """
 
217
    global _bzr_log_filename
 
218
 
 
219
    def _open_or_create_log_file(filename):
 
220
        """Open existing log file, or create with ownership and permissions
 
221
 
 
222
        It inherits the ownership and permissions (masked by umask) from
 
223
        the containing directory to cope better with being run under sudo
 
224
        with $HOME still set to the user's homedir.
 
225
        """
 
226
        flags = os.O_WRONLY | os.O_APPEND | osutils.O_TEXT
 
227
        while True:
 
228
            try:
 
229
                fd = os.open(filename, flags)
 
230
                break
 
231
            except OSError, e:
 
232
                if e.errno != errno.ENOENT:
 
233
                    raise
 
234
            try:
 
235
                fd = os.open(filename, flags | os.O_CREAT | os.O_EXCL, 0666)
 
236
            except OSError, e:
 
237
                if e.errno != errno.EEXIST:
 
238
                    raise
 
239
            else:
 
240
                osutils.copy_ownership_from_path(filename)
 
241
                break
 
242
        return os.fdopen(fd, 'at', 0) # unbuffered
 
243
 
 
244
 
 
245
    _bzr_log_filename = _get_bzr_log_filename()
 
246
    _rollover_trace_maybe(_bzr_log_filename)
157
247
    try:
158
 
        LINE_BUFFERED = 1
159
 
        #tf = codecs.open(trace_fname, 'at', 'utf8', buffering=LINE_BUFFERED)
160
 
        tf = open(trace_fname, 'at', LINE_BUFFERED)
161
 
        _bzr_log_file = tf
162
 
        # tf.tell() on windows always return 0 until some writing done
163
 
        tf.write('\n')
164
 
        if tf.tell() <= 2:
165
 
            tf.write("this is a debug log for diagnosing/reporting problems in bzr\n")
166
 
            tf.write("you can delete or truncate this file, or include sections in\n")
167
 
            tf.write("bug reports to bazaar@lists.canonical.com\n\n")
168
 
        _file_handler = logging.StreamHandler(tf)
169
 
        fmt = r'[%(process)5d] %(asctime)s.%(msecs)03d %(levelname)s: %(message)s'
170
 
        datefmt = r'%a %H:%M:%S'
171
 
        _file_handler.setFormatter(logging.Formatter(fmt, datefmt))
172
 
        _file_handler.setLevel(logging.DEBUG)
173
 
        logging.getLogger('').addHandler(_file_handler)
174
 
    except IOError, e:
175
 
        warning("failed to open trace file: %s" % (e))
176
 
 
177
 
 
178
 
@deprecated_function(zero_nine)
179
 
def log_exception(msg=None):
180
 
    """Log the last exception to stderr and the trace file.
181
 
 
182
 
    The exception string representation is used as the error
183
 
    summary, unless msg is given.
184
 
    """
185
 
    if msg:
186
 
        error(msg)
187
 
    log_exception_quietly()
 
248
        bzr_log_file = _open_or_create_log_file(_bzr_log_filename)
 
249
        bzr_log_file.write('\n')
 
250
        if bzr_log_file.tell() <= 2:
 
251
            bzr_log_file.write("this is a debug log for diagnosing/reporting problems in bzr\n")
 
252
            bzr_log_file.write("you can delete or truncate this file, or include sections in\n")
 
253
            bzr_log_file.write("bug reports to https://bugs.launchpad.net/bzr/+filebug\n\n")
 
254
 
 
255
        return bzr_log_file
 
256
 
 
257
    except EnvironmentError, e:
 
258
        # If we are failing to open the log, then most likely logging has not
 
259
        # been set up yet. So we just write to stderr rather than using
 
260
        # 'warning()'. If we using warning(), users get the unhelpful 'no
 
261
        # handlers registered for "bzr"' when something goes wrong on the
 
262
        # server. (bug #503886)
 
263
        sys.stderr.write("failed to open trace file: %s\n" % (e,))
 
264
    # TODO: What should happen if we fail to open the trace file?  Maybe the
 
265
    # objects should be pointed at /dev/null or the equivalent?  Currently
 
266
    # returns None which will cause failures later.
 
267
    return None
 
268
 
 
269
 
 
270
def enable_default_logging():
 
271
    """Configure default logging: messages to stderr and debug to .bzr.log
 
272
 
 
273
    This should only be called once per process.
 
274
 
 
275
    Non-command-line programs embedding bzrlib do not need to call this.  They
 
276
    can instead either pass a file to _push_log_file, or act directly on
 
277
    logging.getLogger("bzr").
 
278
 
 
279
    Output can be redirected away by calling _push_log_file.
 
280
 
 
281
    :return: A memento from push_log_file for restoring the log state.
 
282
    """
 
283
    start_time = osutils.format_local_date(_bzr_log_start_time,
 
284
                                           timezone='local')
 
285
    bzr_log_file = _open_bzr_log()
 
286
    if bzr_log_file is not None:
 
287
        bzr_log_file.write(start_time.encode('utf-8') + '\n')
 
288
    memento = push_log_file(bzr_log_file,
 
289
        r'[%(process)5d] %(asctime)s.%(msecs)03d %(levelname)s: %(message)s',
 
290
        r'%Y-%m-%d %H:%M:%S')
 
291
    # after hooking output into bzr_log, we also need to attach a stderr
 
292
    # handler, writing only at level info and with encoding
 
293
    stderr_handler = EncodedStreamHandler(sys.stderr,
 
294
        osutils.get_terminal_encoding(), 'replace', level=logging.INFO)
 
295
    logging.getLogger('bzr').addHandler(stderr_handler)
 
296
    return memento
 
297
 
 
298
 
 
299
def push_log_file(to_file, log_format=None, date_format=None):
 
300
    """Intercept log and trace messages and send them to a file.
 
301
 
 
302
    :param to_file: A file-like object to which messages will be sent.
 
303
 
 
304
    :returns: A memento that should be passed to _pop_log_file to restore the
 
305
        previously active logging.
 
306
    """
 
307
    global _trace_file
 
308
    # make a new handler
 
309
    new_handler = EncodedStreamHandler(to_file, "utf-8", level=logging.DEBUG)
 
310
    if log_format is None:
 
311
        log_format = '%(levelname)8s  %(message)s'
 
312
    new_handler.setFormatter(logging.Formatter(log_format, date_format))
 
313
    # save and remove any existing log handlers
 
314
    bzr_logger = logging.getLogger('bzr')
 
315
    old_handlers = bzr_logger.handlers[:]
 
316
    del bzr_logger.handlers[:]
 
317
    # set that as the default logger
 
318
    bzr_logger.addHandler(new_handler)
 
319
    bzr_logger.setLevel(logging.DEBUG)
 
320
    # TODO: check if any changes are needed to the root logger
 
321
    #
 
322
    # TODO: also probably need to save and restore the level on bzr_logger.
 
323
    # but maybe we can avoid setting the logger level altogether, and just set
 
324
    # the level on the handler?
 
325
    #
 
326
    # save the old trace file
 
327
    old_trace_file = _trace_file
 
328
    # send traces to the new one
 
329
    _trace_file = to_file
 
330
    result = new_handler, _trace_file
 
331
    return ('log_memento', old_handlers, new_handler, old_trace_file, to_file)
 
332
 
 
333
 
 
334
def pop_log_file((magic, old_handlers, new_handler, old_trace_file, new_trace_file)):
 
335
    """Undo changes to logging/tracing done by _push_log_file.
 
336
 
 
337
    This flushes, but does not close the trace file (so that anything that was
 
338
    in it is output.
 
339
 
 
340
    Takes the memento returned from _push_log_file."""
 
341
    global _trace_file
 
342
    _trace_file = old_trace_file
 
343
    bzr_logger = logging.getLogger('bzr')
 
344
    bzr_logger.removeHandler(new_handler)
 
345
    # must be closed, otherwise logging will try to close it at exit, and the
 
346
    # file will likely already be closed underneath.
 
347
    new_handler.close()
 
348
    bzr_logger.handlers = old_handlers
 
349
    if new_trace_file is not None:
 
350
        new_trace_file.flush()
188
351
 
189
352
 
190
353
def log_exception_quietly():
191
354
    """Log the last exception to the trace file only.
192
355
 
193
 
    Used for exceptions that occur internally and that may be 
194
 
    interesting to developers but not to users.  For example, 
 
356
    Used for exceptions that occur internally and that may be
 
357
    interesting to developers but not to users.  For example,
195
358
    errors loading plugins.
196
359
    """
197
 
    import traceback
198
360
    mutter(traceback.format_exc())
199
361
 
200
362
 
201
 
def enable_default_logging():
202
 
    """Configure default logging to stderr and .bzr.log"""
203
 
    # FIXME: if this is run twice, things get confused
204
 
    global _stderr_handler, _file_handler, _trace_file, _bzr_log_file
205
 
    _stderr_handler = logging.StreamHandler()
206
 
    logging.getLogger('').addHandler(_stderr_handler)
207
 
    _stderr_handler.setLevel(logging.INFO)
208
 
    if not _file_handler:
209
 
        open_tracefile()
210
 
    _trace_file = _bzr_log_file
211
 
    if _file_handler:
212
 
        _file_handler.setLevel(logging.DEBUG)
213
 
    _bzr_logger.setLevel(logging.DEBUG)
 
363
def set_verbosity_level(level):
 
364
    """Set the verbosity level.
 
365
 
 
366
    :param level: -ve for quiet, 0 for normal, +ve for verbose
 
367
    """
 
368
    global _verbosity_level
 
369
    _verbosity_level = level
 
370
    _update_logging_level(level < 0)
 
371
    ui.ui_factory.be_quiet(level < 0)
 
372
 
 
373
 
 
374
def get_verbosity_level():
 
375
    """Get the verbosity level.
 
376
 
 
377
    See set_verbosity_level() for values.
 
378
    """
 
379
    return _verbosity_level
214
380
 
215
381
 
216
382
def be_quiet(quiet=True):
217
 
    global _stderr_handler, _stderr_quiet
218
 
    
219
 
    _stderr_quiet = quiet
220
 
    if quiet:
221
 
        _stderr_handler.setLevel(logging.WARNING)
222
 
    else:
223
 
        _stderr_handler.setLevel(logging.INFO)
 
383
    if quiet:
 
384
        set_verbosity_level(-1)
 
385
    else:
 
386
        set_verbosity_level(0)
 
387
 
 
388
 
 
389
def _update_logging_level(quiet=True):
 
390
    """Hide INFO messages if quiet."""
 
391
    if quiet:
 
392
        _bzr_logger.setLevel(logging.WARNING)
 
393
    else:
 
394
        _bzr_logger.setLevel(logging.INFO)
224
395
 
225
396
 
226
397
def is_quiet():
227
 
    global _stderr_quiet
228
 
    return _stderr_quiet
229
 
 
230
 
 
231
 
def disable_default_logging():
232
 
    """Turn off default log handlers.
233
 
 
234
 
    This is intended to be used by the test framework, which doesn't
235
 
    want leakage from the code-under-test into the main logs.
236
 
    """
237
 
 
238
 
    l = logging.getLogger('')
239
 
    l.removeHandler(_stderr_handler)
240
 
    if _file_handler:
241
 
        l.removeHandler(_file_handler)
242
 
    _trace_file = None
243
 
 
244
 
 
245
 
def enable_test_log(to_file):
246
 
    """Redirect logging to a temporary file for a test
247
 
    
248
 
    returns an opaque reference that should be passed to disable_test_log
249
 
    after the test completes.
250
 
    """
251
 
    disable_default_logging()
252
 
    global _trace_file
253
 
    global _trace_depth
254
 
    hdlr = logging.StreamHandler(to_file)
255
 
    hdlr.setLevel(logging.DEBUG)
256
 
    hdlr.setFormatter(logging.Formatter('%(levelname)8s  %(message)s'))
257
 
    _bzr_logger.addHandler(hdlr)
258
 
    _bzr_logger.setLevel(logging.DEBUG)
259
 
    result = hdlr, _trace_file, _trace_depth
260
 
    _trace_file = to_file
261
 
    _trace_depth += 1
262
 
    return result
263
 
 
264
 
 
265
 
def disable_test_log((test_log_hdlr, old_trace_file, old_trace_depth)):
266
 
    _bzr_logger.removeHandler(test_log_hdlr)
267
 
    test_log_hdlr.close()
268
 
    global _trace_file
269
 
    global _trace_depth
270
 
    _trace_file = old_trace_file
271
 
    _trace_depth = old_trace_depth
272
 
    if not _trace_depth:
273
 
        enable_default_logging()
 
398
    """Is the verbosity level negative?"""
 
399
    return _verbosity_level < 0
 
400
 
 
401
 
 
402
def is_verbose():
 
403
    """Is the verbosity level positive?"""
 
404
    return _verbosity_level > 0
 
405
 
 
406
 
 
407
def debug_memory(message='', short=True):
 
408
    """Write out a memory dump."""
 
409
    if sys.platform == 'win32':
 
410
        from bzrlib import win32utils
 
411
        win32utils.debug_memory_win32api(message=message, short=short)
 
412
    else:
 
413
        _debug_memory_proc(message=message, short=short)
 
414
 
 
415
 
 
416
_short_fields = ('VmPeak', 'VmSize', 'VmRSS')
 
417
 
 
418
def _debug_memory_proc(message='', short=True):
 
419
    try:
 
420
        status_file = file('/proc/%s/status' % os.getpid(), 'rb')
 
421
    except IOError:
 
422
        return
 
423
    try:
 
424
        status = status_file.read()
 
425
    finally:
 
426
        status_file.close()
 
427
    if message:
 
428
        note(message)
 
429
    for line in status.splitlines():
 
430
        if not short:
 
431
            note(line)
 
432
        else:
 
433
            for field in _short_fields:
 
434
                if line.startswith(field):
 
435
                    note(line)
 
436
                    break
 
437
 
 
438
def _dump_memory_usage(err_file):
 
439
    try:
 
440
        try:
 
441
            fd, name = tempfile.mkstemp(prefix="bzr_memdump", suffix=".json")
 
442
            dump_file = os.fdopen(fd, 'w')
 
443
            from meliae import scanner
 
444
            scanner.dump_gc_objects(dump_file)
 
445
            err_file.write("Memory dumped to %s\n" % name)
 
446
        except ImportError:
 
447
            err_file.write("Dumping memory requires meliae module.\n")
 
448
            log_exception_quietly()
 
449
        except:
 
450
            err_file.write("Exception while dumping memory.\n")
 
451
            log_exception_quietly()
 
452
    finally:
 
453
        if dump_file is not None:
 
454
            dump_file.close()
 
455
        elif fd is not None:
 
456
            os.close(fd)
 
457
 
 
458
 
 
459
def _qualified_exception_name(eclass, unqualified_bzrlib_errors=False):
 
460
    """Give name of error class including module for non-builtin exceptions
 
461
 
 
462
    If `unqualified_bzrlib_errors` is True, errors specific to bzrlib will
 
463
    also omit the module prefix.
 
464
    """
 
465
    class_name = eclass.__name__
 
466
    module_name = eclass.__module__
 
467
    if module_name in ("exceptions", "__main__") or (
 
468
            unqualified_bzrlib_errors and module_name == "bzrlib.errors"):
 
469
        return class_name
 
470
    return "%s.%s" % (module_name, class_name)
274
471
 
275
472
 
276
473
def report_exception(exc_info, err_file):
277
 
    exc_type, exc_object, exc_tb = exc_info
 
474
    """Report an exception to err_file (typically stderr) and to .bzr.log.
 
475
 
 
476
    This will show either a full traceback or a short message as appropriate.
 
477
 
 
478
    :return: The appropriate exit code for this error.
 
479
    """
278
480
    # Log the full traceback to ~/.bzr.log
279
481
    log_exception_quietly()
280
 
    if (isinstance(exc_object, IOError)
281
 
        and getattr(exc_object, 'errno', None) == errno.EPIPE):
282
 
        print >>err_file, "bzr: broken pipe"
283
 
    elif isinstance(exc_object, KeyboardInterrupt):
284
 
        print >>err_file, "bzr: interrupted"
 
482
    if 'error' in debug.debug_flags:
 
483
        print_exception(exc_info, err_file)
 
484
        return errors.EXIT_ERROR
 
485
    exc_type, exc_object, exc_tb = exc_info
 
486
    if isinstance(exc_object, KeyboardInterrupt):
 
487
        err_file.write("bzr: interrupted\n")
 
488
        return errors.EXIT_ERROR
 
489
    elif isinstance(exc_object, MemoryError):
 
490
        err_file.write("bzr: out of memory\n")
 
491
        if 'mem_dump' in debug.debug_flags:
 
492
            _dump_memory_usage(err_file)
 
493
        else:
 
494
            err_file.write("Use -Dmem_dump to dump memory to a file.\n")
 
495
        return errors.EXIT_ERROR
 
496
    elif isinstance(exc_object, ImportError) \
 
497
        and str(exc_object).startswith("No module named "):
 
498
        report_user_error(exc_info, err_file,
 
499
            'You may need to install this Python library separately.')
 
500
        return errors.EXIT_ERROR
285
501
    elif not getattr(exc_object, 'internal_error', True):
286
502
        report_user_error(exc_info, err_file)
287
 
    elif isinstance(exc_object, (OSError, IOError)):
 
503
        return errors.EXIT_ERROR
 
504
    elif osutils.is_environment_error(exc_object):
 
505
        if getattr(exc_object, 'errno', None) == errno.EPIPE:
 
506
            err_file.write("bzr: broken pipe\n")
 
507
            return errors.EXIT_ERROR
288
508
        # Might be nice to catch all of these and show them as something more
289
509
        # specific, but there are too many cases at the moment.
290
510
        report_user_error(exc_info, err_file)
 
511
        return errors.EXIT_ERROR
291
512
    else:
292
513
        report_bug(exc_info, err_file)
 
514
        return errors.EXIT_INTERNAL_ERROR
 
515
 
 
516
 
 
517
def print_exception(exc_info, err_file):
 
518
    exc_type, exc_object, exc_tb = exc_info
 
519
    err_file.write("bzr: ERROR: %s.%s: %s\n" % (
 
520
        exc_type.__module__, exc_type.__name__, exc_object))
 
521
    err_file.write('\n')
 
522
    traceback.print_exception(exc_type, exc_object, exc_tb, file=err_file)
293
523
 
294
524
 
295
525
# TODO: Should these be specially encoding the output?
296
 
def report_user_error(exc_info, err_file):
 
526
def report_user_error(exc_info, err_file, advice=None):
297
527
    """Report to err_file an error that's not an internal error.
298
528
 
299
529
    These don't get a traceback unless -Derror was given.
 
530
 
 
531
    :param exc_info: 3-tuple from sys.exc_info()
 
532
    :param advice: Extra advice to the user to be printed following the
 
533
        exception.
300
534
    """
301
 
    if 'error' in debug.debug_flags:
302
 
        report_bug(exc_info, err_file)
303
 
        return
304
 
    print >>err_file, "bzr: ERROR:", str(exc_info[1])
 
535
    err_file.write("bzr: ERROR: %s\n" % (exc_info[1],))
 
536
    if advice:
 
537
        err_file.write("%s\n" % (advice,))
305
538
 
306
539
 
307
540
def report_bug(exc_info, err_file):
308
541
    """Report an exception that probably indicates a bug in bzr"""
309
 
    import traceback
310
 
    exc_type, exc_object, exc_tb = exc_info
311
 
    print >>err_file, "bzr: ERROR: %s.%s: %s" % (
312
 
        exc_type.__module__, exc_type.__name__, exc_object)
313
 
    print >>err_file
314
 
    traceback.print_exception(exc_type, exc_object, exc_tb, file=err_file)
315
 
    print >>err_file
316
 
    print >>err_file, 'bzr %s on python %s (%s)' % \
317
 
                       (bzrlib.__version__,
318
 
                        '.'.join(map(str, sys.version_info)),
319
 
                        sys.platform)
320
 
    print >>err_file, 'arguments: %r' % sys.argv
321
 
    print >>err_file
322
 
    print >>err_file, "** please send this report to bazaar@lists.ubuntu.com"
 
542
    from bzrlib.crash import report_bug
 
543
    report_bug(exc_info, err_file)
 
544
 
 
545
 
 
546
def _flush_stdout_stderr():
 
547
    # called from the bzrlib library finalizer returned by bzrlib.initialize()
 
548
    try:
 
549
        sys.stdout.flush()
 
550
        sys.stderr.flush()
 
551
    except ValueError, e:
 
552
        # On Windows, I get ValueError calling stdout.flush() on a closed
 
553
        # handle
 
554
        pass
 
555
    except IOError, e:
 
556
        import errno
 
557
        if e.errno in [errno.EINVAL, errno.EPIPE]:
 
558
            pass
 
559
        else:
 
560
            raise
 
561
 
 
562
 
 
563
def _flush_trace():
 
564
    # called from the bzrlib library finalizer returned by bzrlib.initialize()
 
565
    global _trace_file
 
566
    if _trace_file:
 
567
        _trace_file.flush()
 
568
 
 
569
 
 
570
class EncodedStreamHandler(logging.Handler):
 
571
    """Robustly write logging events to a stream using the specified encoding
 
572
 
 
573
    Messages are expected to be formatted to unicode, but UTF-8 byte strings
 
574
    are also accepted. An error during formatting or a str message in another
 
575
    encoding will be quitely noted as an error in the Bazaar log file.
 
576
 
 
577
    The stream is not closed so sys.stdout or sys.stderr may be passed.
 
578
    """
 
579
 
 
580
    def __init__(self, stream, encoding=None, errors='strict', level=0):
 
581
        logging.Handler.__init__(self, level)
 
582
        self.stream = stream
 
583
        if encoding is None:
 
584
            encoding = getattr(stream, "encoding", "ascii")
 
585
        self.encoding = encoding
 
586
        self.errors = errors
 
587
 
 
588
    def flush(self):
 
589
        flush = getattr(self.stream, "flush", None)
 
590
        if flush is not None:
 
591
            flush()
 
592
 
 
593
    def emit(self, record):
 
594
        try:
 
595
            line = self.format(record)
 
596
            if not isinstance(line, unicode):
 
597
                line = line.decode("utf-8")
 
598
            self.stream.write(line.encode(self.encoding, self.errors) + "\n")
 
599
        except Exception:
 
600
            log_exception_quietly()
 
601
            # Try saving the details that would have been logged in some form
 
602
            msg = args = "<Unformattable>"
 
603
            try:
 
604
                msg = repr(record.msg).encode("ascii")
 
605
                args = repr(record.args).encode("ascii")
 
606
            except Exception:
 
607
                pass
 
608
            # Using mutter() bypasses the logging module and writes directly
 
609
            # to the file so there's no danger of getting into a loop here.
 
610
            mutter("Logging record unformattable: %s %% %s", msg, args)
 
611
 
 
612
 
 
613
class Config(object):
 
614
    """Configuration of message tracing in bzrlib.
 
615
 
 
616
    This implements the context manager protocol and should manage any global
 
617
    variables still used. The default config used is DefaultConfig, but
 
618
    embedded uses of bzrlib may wish to use a custom manager.
 
619
    """
 
620
 
 
621
    def __enter__(self):
 
622
        return self # This is bound to the 'as' clause in a with statement.
 
623
 
 
624
    def __exit__(self, exc_type, exc_val, exc_tb):
 
625
        return False # propogate exceptions.
 
626
 
 
627
 
 
628
class DefaultConfig(Config):
 
629
    """A default configuration for tracing of messages in bzrlib.
 
630
 
 
631
    This implements the context manager protocol.
 
632
    """
 
633
 
 
634
    def __enter__(self):
 
635
        self._original_filename = _bzr_log_filename
 
636
        self._original_state = enable_default_logging()
 
637
        return self # This is bound to the 'as' clause in a with statement.
 
638
 
 
639
    def __exit__(self, exc_type, exc_val, exc_tb):
 
640
        pop_log_file(self._original_state)
 
641
        global _bzr_log_filename
 
642
        _bzr_log_filename = self._original_filename
 
643
        return False # propogate exceptions.