~bzr-pqm/bzr/bzr.dev

1 by mbp at sourcefrog
import from baz patch-364
1
# This program is free software; you can redistribute it and/or modify
2
# it under the terms of the GNU General Public License as published by
3
# the Free Software Foundation; either version 2 of the License, or
4
# (at your option) any later version.
5
6
# This program is distributed in the hope that it will be useful,
7
# but WITHOUT ANY WARRANTY; without even the implied warranty of
8
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9
# GNU General Public License for more details.
10
11
# You should have received a copy of the GNU General Public License
12
# along with this program; if not, write to the Free Software
13
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
14
15
16
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
17
__author__ = "Martin Pool <mbp@canonical.com>"
18
19
344 by Martin Pool
- It's not an error to use the library without
20
"""Messages and logging for bazaar-ng
21
22
Nothing is actually logged unless you call bzrlib.open_tracefile().
23
"""
24
25
359 by Martin Pool
- pychecker fixups
26
import sys, os
1 by mbp at sourcefrog
import from baz patch-364
27
28
######################################################################
29
# messages and logging
30
59 by mbp at sourcefrog
lift out tracefile creation code
31
global _tracefile, _starttime
161 by mbp at sourcefrog
pychecker warnings
32
_tracefile = None
59 by mbp at sourcefrog
lift out tracefile creation code
33
1 by mbp at sourcefrog
import from baz patch-364
34
# used to have % (os.environ['USER'], time.time(), os.getpid()), 'w')
184 by mbp at sourcefrog
pychecker fixups
35
_starttime = None
1 by mbp at sourcefrog
import from baz patch-364
36
37
# If false, notes also go to stdout; should replace this with --silent
38
# at some point.
39
silent = False
40
115 by mbp at sourcefrog
todo
41
257 by Martin Pool
- Write less startup junk to .bzr.log
42
# fix this if we ever fork within python
43
_mypid = os.getpid()
44
_logprefix = '[%d] ' % _mypid
45
46
47
def _write_trace(msg):
344 by Martin Pool
- It's not an error to use the library without
48
    if _tracefile:
49
        _tracefile.write(_logprefix + msg + '\n')
257 by Martin Pool
- Write less startup junk to .bzr.log
50
51
70 by mbp at sourcefrog
Prepare for smart recursive add.
52
def warning(msg):
257 by Martin Pool
- Write less startup junk to .bzr.log
53
    sys.stderr.write('bzr: warning: ' + msg + '\n')
54
    _write_trace('warning: ' + msg)
55
56
57
mutter = _write_trace
1 by mbp at sourcefrog
import from baz patch-364
58
59
60
def note(msg):
61
    b = '* ' + str(msg) + '\n'
62
    if not silent:
63
        sys.stderr.write(b)
257 by Martin Pool
- Write less startup junk to .bzr.log
64
    _write_trace('note: ' + msg)
1 by mbp at sourcefrog
import from baz patch-364
65
66
67
def log_error(msg):
257 by Martin Pool
- Write less startup junk to .bzr.log
68
    sys.stderr.write(msg + '\n')
69
    _write_trace(msg)
70
71
261 by Martin Pool
- auto-rollover of .bzr.log
72
def _rollover_trace_maybe(trace_fname):
359 by Martin Pool
- pychecker fixups
73
    import stat
261 by Martin Pool
- auto-rollover of .bzr.log
74
    try:
75
        size = os.stat(trace_fname)[stat.ST_SIZE]
333 by Martin Pool
- allow trace file to grow up to 4MB
76
        if size <= 4 << 20:
261 by Martin Pool
- auto-rollover of .bzr.log
77
            return
78
        old_fname = trace_fname + '.old'
79
80
        try:
81
            # must remove before rename on windows
82
            os.remove(old_fname)
83
        except OSError:
84
            pass
85
86
        try:
87
            # might fail if in use on windows
88
            os.rename(trace_fname, old_fname)
89
        except OSError:
90
            pass
91
    except OSError:
92
        return
93
94
95
397 by Martin Pool
- open_tracefile takes a tracefilename parameter
96
def open_tracefile(argv=[], tracefilename='~/.bzr.log'):
59 by mbp at sourcefrog
lift out tracefile creation code
97
    # Messages are always written to here, so that we have some
98
    # information if something goes wrong.  In a future version this
99
    # file will be removed on successful completion.
100
    global _starttime, _tracefile
359 by Martin Pool
- pychecker fixups
101
    import stat, codecs
59 by mbp at sourcefrog
lift out tracefile creation code
102
103
    _starttime = os.times()[4]
104
397 by Martin Pool
- open_tracefile takes a tracefilename parameter
105
    trace_fname = os.path.join(os.path.expanduser(tracefilename))
261 by Martin Pool
- auto-rollover of .bzr.log
106
    _rollover_trace_maybe(trace_fname)
257 by Martin Pool
- Write less startup junk to .bzr.log
107
108
    # buffering=1 means line buffered
403 by Martin Pool
- Don't give an error if the trace file can't be opened
109
    try:
110
        _tracefile = codecs.open(trace_fname, 'at', 'utf8', buffering=1)
111
        t = _tracefile
112
113
        if os.fstat(t.fileno())[stat.ST_SIZE] == 0:
114
            t.write("\nthis is a debug log for diagnosing/reporting problems in bzr\n")
115
            t.write("you can delete or truncate this file, or include sections in\n")
116
            t.write("bug reports to bazaar-ng@lists.canonical.com\n\n")
117
118
        import bzrlib
119
        _write_trace('bzr %s invoked on python %s (%s)'
120
                     % (bzrlib.__version__,
121
                        '.'.join(map(str, sys.version_info)),
122
                        sys.platform))
123
124
        _write_trace('  arguments: %r' % argv)
125
        _write_trace('  working dir: ' + os.getcwdu())
126
    except IOError, e:
127
        warning("failed to open trace file: %s" % (e))
260 by Martin Pool
- remove atexit() dependency for writing out execution times
128
129
def close_trace():
59 by mbp at sourcefrog
lift out tracefile creation code
130
    times = os.times()
131
    mutter("finished, %.3fu/%.3fs cpu, %.3fu/%.3fs cum, %.3f elapsed"
132
           % (times[:4] + ((times[4] - _starttime),)))
133
134
135
359 by Martin Pool
- pychecker fixups
136
def log_exception():
137
    """Log the last exception into the trace file."""
360 by Martin Pool
- use cgitb to get more detailed traceback in the
138
    import cgitb
139
    s = cgitb.text(sys.exc_info())
140
    for l in s.split('\n'):
269 by Martin Pool
- Put proper prefix at start of exceptions in trace file
141
        _write_trace(l)
142
        
263 by Martin Pool
factor out code to log exceptions
143