##// END OF EJS Templates
blackbox: minor code reordering...
marmoute -
r33129:7dc090fa default
parent child Browse files
Show More
@@ -1,251 +1,253 b''
1 1 # blackbox.py - log repository events to a file for post-mortem debugging
2 2 #
3 3 # Copyright 2010 Nicolas Dumazet
4 4 # Copyright 2013 Facebook, Inc.
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 """log repository events to a blackbox for debugging
10 10
11 11 Logs event information to .hg/blackbox.log to help debug and diagnose problems.
12 12 The events that get logged can be configured via the blackbox.track config key.
13 13
14 14 Examples::
15 15
16 16 [blackbox]
17 17 track = *
18 18 # dirty is *EXPENSIVE* (slow);
19 19 # each log entry indicates `+` if the repository is dirty, like :hg:`id`.
20 20 dirty = True
21 21 # record the source of log messages
22 22 logsource = True
23 23
24 24 [blackbox]
25 25 track = command, commandfinish, commandexception, exthook, pythonhook
26 26
27 27 [blackbox]
28 28 track = incoming
29 29
30 30 [blackbox]
31 31 # limit the size of a log file
32 32 maxsize = 1.5 MB
33 33 # rotate up to N log files when the current one gets too big
34 34 maxfiles = 3
35 35
36 36 """
37 37
38 38 from __future__ import absolute_import
39 39
40 40 import errno
41 41 import re
42 42
43 43 from mercurial.i18n import _
44 44 from mercurial.node import hex
45 45
46 46 from mercurial import (
47 47 registrar,
48 48 ui as uimod,
49 49 util,
50 50 )
51 51
52 cmdtable = {}
53 command = registrar.command(cmdtable)
54 52 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
55 53 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
56 54 # be specifying the version(s) of Mercurial they are tested with, or
57 55 # leave the attribute unspecified.
58 56 testedwith = 'ships-with-hg-core'
57
58 cmdtable = {}
59 command = registrar.command(cmdtable)
60
59 61 lastui = None
60 62
61 63 filehandles = {}
62 64
63 65 def _openlog(vfs):
64 66 path = vfs.join('blackbox.log')
65 67 if path in filehandles:
66 68 return filehandles[path]
67 69 filehandles[path] = fp = vfs('blackbox.log', 'a')
68 70 return fp
69 71
70 72 def _closelog(vfs):
71 73 path = vfs.join('blackbox.log')
72 74 fp = filehandles[path]
73 75 del filehandles[path]
74 76 fp.close()
75 77
76 78 def wrapui(ui):
77 79 class blackboxui(ui.__class__):
78 80 def __init__(self, src=None):
79 81 super(blackboxui, self).__init__(src)
80 82 if src is None:
81 83 self._partialinit()
82 84 else:
83 85 self._bbfp = getattr(src, '_bbfp', None)
84 86 self._bbinlog = False
85 87 self._bbrepo = getattr(src, '_bbrepo', None)
86 88 self._bbvfs = getattr(src, '_bbvfs', None)
87 89
88 90 def _partialinit(self):
89 91 if util.safehasattr(self, '_bbvfs'):
90 92 return
91 93 self._bbfp = None
92 94 self._bbinlog = False
93 95 self._bbrepo = None
94 96 self._bbvfs = None
95 97
96 98 def copy(self):
97 99 self._partialinit()
98 100 return self.__class__(self)
99 101
100 102 @util.propertycache
101 103 def track(self):
102 104 return self.configlist('blackbox', 'track', ['*'])
103 105
104 106 def _openlogfile(self):
105 107 def rotate(oldpath, newpath):
106 108 try:
107 109 self._bbvfs.unlink(newpath)
108 110 except OSError as err:
109 111 if err.errno != errno.ENOENT:
110 112 self.debug("warning: cannot remove '%s': %s\n" %
111 113 (newpath, err.strerror))
112 114 try:
113 115 if newpath:
114 116 self._bbvfs.rename(oldpath, newpath)
115 117 except OSError as err:
116 118 if err.errno != errno.ENOENT:
117 119 self.debug("warning: cannot rename '%s' to '%s': %s\n" %
118 120 (newpath, oldpath, err.strerror))
119 121
120 122 fp = _openlog(self._bbvfs)
121 123 maxsize = self.configbytes('blackbox', 'maxsize', 1048576)
122 124 if maxsize > 0:
123 125 st = self._bbvfs.fstat(fp)
124 126 if st.st_size >= maxsize:
125 127 path = fp.name
126 128 _closelog(self._bbvfs)
127 129 maxfiles = self.configint('blackbox', 'maxfiles', 7)
128 130 for i in xrange(maxfiles - 1, 1, -1):
129 131 rotate(oldpath='%s.%d' % (path, i - 1),
130 132 newpath='%s.%d' % (path, i))
131 133 rotate(oldpath=path,
132 134 newpath=maxfiles > 0 and path + '.1')
133 135 fp = _openlog(self._bbvfs)
134 136 return fp
135 137
136 138 def _bbwrite(self, fmt, *args):
137 139 self._bbfp.write(fmt % args)
138 140 self._bbfp.flush()
139 141
140 142 def log(self, event, *msg, **opts):
141 143 global lastui
142 144 super(blackboxui, self).log(event, *msg, **opts)
143 145 self._partialinit()
144 146
145 147 if not '*' in self.track and not event in self.track:
146 148 return
147 149
148 150 if self._bbfp:
149 151 ui = self
150 152 elif self._bbvfs:
151 153 try:
152 154 self._bbfp = self._openlogfile()
153 155 except (IOError, OSError) as err:
154 156 self.debug('warning: cannot write to blackbox.log: %s\n' %
155 157 err.strerror)
156 158 del self._bbvfs
157 159 self._bbfp = None
158 160 ui = self
159 161 else:
160 162 # certain ui instances exist outside the context of
161 163 # a repo, so just default to the last blackbox that
162 164 # was seen.
163 165 ui = lastui
164 166
165 167 if not ui or not ui._bbfp:
166 168 return
167 169 if not lastui or ui._bbrepo:
168 170 lastui = ui
169 171 if ui._bbinlog:
170 172 # recursion guard
171 173 return
172 174 try:
173 175 ui._bbinlog = True
174 176 default = self.configdate('devel', 'default-date')
175 177 date = util.datestr(default, '%Y/%m/%d %H:%M:%S')
176 178 user = util.getuser()
177 179 pid = '%d' % util.getpid()
178 180 formattedmsg = msg[0] % msg[1:]
179 181 rev = '(unknown)'
180 182 changed = ''
181 183 if ui._bbrepo:
182 184 ctx = ui._bbrepo[None]
183 185 parents = ctx.parents()
184 186 rev = ('+'.join([hex(p.node()) for p in parents]))
185 187 if (ui.configbool('blackbox', 'dirty', False) and (
186 188 any(ui._bbrepo.status()) or
187 189 any(ctx.sub(s).dirty() for s in ctx.substate)
188 190 )):
189 191 changed = '+'
190 192 if ui.configbool('blackbox', 'logsource', False):
191 193 src = ' [%s]' % event
192 194 else:
193 195 src = ''
194 196 try:
195 197 ui._bbwrite('%s %s @%s%s (%s)%s> %s',
196 198 date, user, rev, changed, pid, src, formattedmsg)
197 199 except IOError as err:
198 200 self.debug('warning: cannot write to blackbox.log: %s\n' %
199 201 err.strerror)
200 202 finally:
201 203 ui._bbinlog = False
202 204
203 205 def setrepo(self, repo):
204 206 self._bbfp = None
205 207 self._bbinlog = False
206 208 self._bbrepo = repo
207 209 self._bbvfs = repo.vfs
208 210
209 211 ui.__class__ = blackboxui
210 212 uimod.ui = blackboxui
211 213
212 214 def uisetup(ui):
213 215 wrapui(ui)
214 216
215 217 def reposetup(ui, repo):
216 218 # During 'hg pull' a httppeer repo is created to represent the remote repo.
217 219 # It doesn't have a .hg directory to put a blackbox in, so we don't do
218 220 # the blackbox setup for it.
219 221 if not repo.local():
220 222 return
221 223
222 224 if util.safehasattr(ui, 'setrepo'):
223 225 ui.setrepo(repo)
224 226
225 227 @command('^blackbox',
226 228 [('l', 'limit', 10, _('the number of events to show')),
227 229 ],
228 230 _('hg blackbox [OPTION]...'))
229 231 def blackbox(ui, repo, *revs, **opts):
230 232 '''view the recent repository events
231 233 '''
232 234
233 235 if not repo.vfs.exists('blackbox.log'):
234 236 return
235 237
236 238 limit = opts.get('limit')
237 239 fp = repo.vfs('blackbox.log', 'r')
238 240 lines = fp.read().split('\n')
239 241
240 242 count = 0
241 243 output = []
242 244 for line in reversed(lines):
243 245 if count >= limit:
244 246 break
245 247
246 248 # count the commands by matching lines like: 2013/01/23 19:13:36 root>
247 249 if re.match('^\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} .*> .*', line):
248 250 count += 1
249 251 output.append(line)
250 252
251 253 ui.status('\n'.join(reversed(output)))
General Comments 0
You need to be logged in to leave comments. Login now