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
17
17
"""Messages and logging for bazaar-ng.
131
131
error = _bzr_logger.error
134
_last_mutter_flush_time = None
134
136
def mutter(fmt, *args):
137
global _last_mutter_flush_time
135
138
if _trace_file is None:
137
140
if (getattr(_trace_file, 'closed', None) is not None) and _trace_file.closed:
152
155
out = fmt % tuple(real_args)
155
timestamp = '%0.3f ' % (time.time() - _bzr_log_start_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
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:
170
_last_mutter_flush_time = now
162
173
def mutter_callsite(stacklevel, fmt, *args):
207
218
def _open_bzr_log():
208
"""Open the .bzr.log trace file.
219
"""Open the .bzr.log trace file.
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.
235
252
def enable_default_logging():
236
253
"""Configure default logging: messages to stderr and debug to .bzr.log
238
255
This should only be called once per process.
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").
244
261
Output can be redirected away by calling _push_log_file.
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,
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)
310
334
new_trace_file.flush()
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
317
:returns: an opaque reference that should be passed to disable_test_log
318
after the test completes.
320
return push_log_file(to_file)
323
@symbol_versioning.deprecated_function(symbol_versioning.one_two)
324
def disable_test_log(memento):
325
return pop_log_file(memento)
328
337
def log_exception_quietly():
329
338
"""Log the last exception to the trace file only.
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.
335
344
mutter(traceback.format_exc())
379
388
return _verbosity_level > 0
382
@symbol_versioning.deprecated_function(symbol_versioning.one_two)
383
def disable_default_logging():
384
"""Turn off default log handlers.
386
Don't call this method, use _push_log_file and _pop_log_file instead.
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)
397
_debug_memory_proc(message=message, short=short)
400
_short_fields = ('VmPeak', 'VmSize', 'VmRSS')
402
def _debug_memory_proc(message='', short=True):
404
status_file = file('/proc/%s/status' % os.getpid(), 'rb')
408
status = status_file.read()
413
for line in status.splitlines():
417
for field in _short_fields:
418
if line.startswith(field):
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,
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)
456
err_file.write('bzr %s on python %s (%s)\n' % \
458
bzrlib._format_version_tuple(sys.version_info),
460
err_file.write('arguments: %r\n' % sys.argv)
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__))
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.
489
from bzrlib.crash import report_bug
490
report_bug(exc_info, err_file)