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