~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/trace.py

  • Committer: Danny van Heumen
  • Date: 2010-03-09 21:42:11 UTC
  • mto: (4634.139.5 2.0)
  • mto: This revision was merged to the branch mainline in revision 5160.
  • Revision ID: danny@dannyvanheumen.nl-20100309214211-iqh42x6qcikgd9p3
Reverted now-useless TODO list.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
17
"""Messages and logging for bazaar-ng.
18
18
 
131
131
error =     _bzr_logger.error
132
132
 
133
133
 
 
134
_last_mutter_flush_time = None
 
135
 
134
136
def mutter(fmt, *args):
 
137
    global _last_mutter_flush_time
135
138
    if _trace_file is None:
136
139
        return
137
140
    if (getattr(_trace_file, 'closed', None) is not None) and _trace_file.closed:
152
155
        out = fmt % tuple(real_args)
153
156
    else:
154
157
        out = fmt
155
 
    timestamp = '%0.3f  ' % (time.time() - _bzr_log_start_time,)
 
158
    now = time.time()
 
159
    timestamp = '%0.3f  ' % (now - _bzr_log_start_time,)
156
160
    out = timestamp + out + '\n'
157
161
    _trace_file.write(out)
158
 
    # no need to flush here, the trace file is now linebuffered when it's
159
 
    # opened.
 
162
    # We flush if we haven't flushed for a few seconds. We don't want to flush
 
163
    # on every mutter, but when a command takes a while, it can be nice to see
 
164
    # updates in the debug log.
 
165
    if (_last_mutter_flush_time is None
 
166
        or (now - _last_mutter_flush_time) > 2.0):
 
167
        flush = getattr(_trace_file, 'flush', None)
 
168
        if flush is not None:
 
169
            flush()
 
170
        _last_mutter_flush_time = now
160
171
 
161
172
 
162
173
def mutter_callsite(stacklevel, fmt, *args):
205
216
 
206
217
 
207
218
def _open_bzr_log():
208
 
    """Open the .bzr.log trace file.  
 
219
    """Open the .bzr.log trace file.
209
220
 
210
221
    If the log is more than a particular length, the old file is renamed to
211
222
    .bzr.log.old and a new file is started.  Otherwise, we append to the
226
237
            bzr_log_file.write("bug reports to https://bugs.launchpad.net/bzr/+filebug\n\n")
227
238
        return bzr_log_file
228
239
    except IOError, e:
229
 
        warning("failed to open trace file: %s" % (e))
 
240
        # If we are failing to open the log, then most likely logging has not
 
241
        # been set up yet. So we just write to stderr rather than using
 
242
        # 'warning()'. If we using warning(), users get the unhelpful 'no
 
243
        # handlers registered for "bzr"' when something goes wrong on the
 
244
        # server. (bug #503886)
 
245
        sys.stderr.write("failed to open trace file: %s\n" % (e,))
230
246
    # TODO: What should happen if we fail to open the trace file?  Maybe the
231
247
    # objects should be pointed at /dev/null or the equivalent?  Currently
232
248
    # returns None which will cause failures later.
 
249
    return None
233
250
 
234
251
 
235
252
def enable_default_logging():
236
253
    """Configure default logging: messages to stderr and debug to .bzr.log
237
 
    
 
254
 
238
255
    This should only be called once per process.
239
256
 
240
257
    Non-command-line programs embedding bzrlib do not need to call this.  They
241
258
    can instead either pass a file to _push_log_file, or act directly on
242
259
    logging.getLogger("bzr").
243
 
    
 
260
 
244
261
    Output can be redirected away by calling _push_log_file.
245
262
    """
 
263
    # Do this before we open the log file, so we prevent
 
264
    # get_terminal_encoding() from mutter()ing multiple times
 
265
    term_encoding = osutils.get_terminal_encoding()
 
266
    start_time = osutils.format_local_date(_bzr_log_start_time,
 
267
                                           timezone='local')
246
268
    # create encoded wrapper around stderr
247
269
    bzr_log_file = _open_bzr_log()
 
270
    if bzr_log_file is not None:
 
271
        bzr_log_file.write(start_time.encode('utf-8') + '\n')
248
272
    push_log_file(bzr_log_file,
249
273
        r'[%(process)5d] %(asctime)s.%(msecs)03d %(levelname)s: %(message)s',
250
274
        r'%Y-%m-%d %H:%M:%S')
251
275
    # after hooking output into bzr_log, we also need to attach a stderr
252
276
    # handler, writing only at level info and with encoding
253
 
    writer_factory = codecs.getwriter(osutils.get_terminal_encoding())
 
277
    writer_factory = codecs.getwriter(term_encoding)
254
278
    encoded_stderr = writer_factory(sys.stderr, errors='replace')
255
279
    stderr_handler = logging.StreamHandler(encoded_stderr)
256
280
    stderr_handler.setLevel(logging.INFO)
262
286
 
263
287
    :param to_file: A file-like object to which messages will be sent.
264
288
 
265
 
    :returns: A memento that should be passed to _pop_log_file to restore the 
 
289
    :returns: A memento that should be passed to _pop_log_file to restore the
266
290
    previously active logging.
267
291
    """
268
292
    global _trace_file
297
321
    """Undo changes to logging/tracing done by _push_log_file.
298
322
 
299
323
    This flushes, but does not close the trace file.
300
 
    
 
324
 
301
325
    Takes the memento returned from _push_log_file."""
302
326
    global _trace_file
303
327
    _trace_file = old_trace_file
310
334
    new_trace_file.flush()
311
335
 
312
336
 
313
 
@symbol_versioning.deprecated_function(symbol_versioning.one_two)
314
 
def enable_test_log(to_file):
315
 
    """Redirect logging to a temporary file for a test
316
 
    
317
 
    :returns: an opaque reference that should be passed to disable_test_log
318
 
    after the test completes.
319
 
    """
320
 
    return push_log_file(to_file)
321
 
 
322
 
 
323
 
@symbol_versioning.deprecated_function(symbol_versioning.one_two)
324
 
def disable_test_log(memento):
325
 
    return pop_log_file(memento)
326
 
 
327
 
 
328
337
def log_exception_quietly():
329
338
    """Log the last exception to the trace file only.
330
339
 
331
 
    Used for exceptions that occur internally and that may be 
332
 
    interesting to developers but not to users.  For example, 
 
340
    Used for exceptions that occur internally and that may be
 
341
    interesting to developers but not to users.  For example,
333
342
    errors loading plugins.
334
343
    """
335
344
    mutter(traceback.format_exc())
379
388
    return _verbosity_level > 0
380
389
 
381
390
 
382
 
@symbol_versioning.deprecated_function(symbol_versioning.one_two)
383
 
def disable_default_logging():
384
 
    """Turn off default log handlers.
385
 
 
386
 
    Don't call this method, use _push_log_file and _pop_log_file instead.
387
 
    """
388
 
    pass
 
391
def debug_memory(message='', short=True):
 
392
    """Write out a memory dump."""
 
393
    if sys.platform == 'win32':
 
394
        from bzrlib import win32utils
 
395
        win32utils.debug_memory_win32api(message=message, short=short)
 
396
    else:
 
397
        _debug_memory_proc(message=message, short=short)
 
398
 
 
399
 
 
400
_short_fields = ('VmPeak', 'VmSize', 'VmRSS')
 
401
 
 
402
def _debug_memory_proc(message='', short=True):
 
403
    try:
 
404
        status_file = file('/proc/%s/status' % os.getpid(), 'rb')
 
405
    except IOError:
 
406
        return
 
407
    try:
 
408
        status = status_file.read()
 
409
    finally:
 
410
        status_file.close()
 
411
    if message:
 
412
        note(message)
 
413
    for line in status.splitlines():
 
414
        if not short:
 
415
            note(line)
 
416
        else:
 
417
            for field in _short_fields:
 
418
                if line.startswith(field):
 
419
                    note(line)
 
420
                    break
389
421
 
390
422
 
391
423
def report_exception(exc_info, err_file):
405
437
    elif isinstance(exc_object, KeyboardInterrupt):
406
438
        err_file.write("bzr: interrupted\n")
407
439
        return errors.EXIT_ERROR
 
440
    elif isinstance(exc_object, MemoryError):
 
441
        err_file.write("bzr: out of memory\n")
 
442
        return errors.EXIT_ERROR
408
443
    elif isinstance(exc_object, ImportError) \
409
444
        and str(exc_object).startswith("No module named "):
410
445
        report_user_error(exc_info, err_file,
451
486
 
452
487
def report_bug(exc_info, err_file):
453
488
    """Report an exception that probably indicates a bug in bzr"""
454
 
    print_exception(exc_info, err_file)
455
 
    err_file.write('\n')
456
 
    err_file.write('bzr %s on python %s (%s)\n' % \
457
 
                       (bzrlib.__version__,
458
 
                        bzrlib._format_version_tuple(sys.version_info),
459
 
                        sys.platform))
460
 
    err_file.write('arguments: %r\n' % sys.argv)
461
 
    err_file.write(
462
 
        'encoding: %r, fsenc: %r, lang: %r\n' % (
463
 
            osutils.get_user_encoding(), sys.getfilesystemencoding(),
464
 
            os.environ.get('LANG')))
465
 
    err_file.write("plugins:\n")
466
 
    for name, a_plugin in sorted(plugin.plugins().items()):
467
 
        err_file.write("  %-20s %s [%s]\n" %
468
 
            (name, a_plugin.path(), a_plugin.__version__))
469
 
    err_file.write(
470
 
"""\
471
 
*** Bazaar has encountered an internal error.
472
 
    Please report a bug at https://bugs.launchpad.net/bzr/+filebug
473
 
    including this traceback, and a description of what you
474
 
    were doing when the error occurred.
475
 
""")
 
489
    from bzrlib.crash import report_bug
 
490
    report_bug(exc_info, err_file)