##// END OF EJS Templates
blackbox: inline _bbwrite...
Jun Wu -
r34110:50df6cf2 default
parent child Browse files
Show More
@@ -1,252 +1,251 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 52 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
53 53 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
54 54 # be specifying the version(s) of Mercurial they are tested with, or
55 55 # leave the attribute unspecified.
56 56 testedwith = 'ships-with-hg-core'
57 57
58 58 cmdtable = {}
59 59 command = registrar.command(cmdtable)
60 60
61 61 configtable = {}
62 62 configitem = registrar.configitem(configtable)
63 63
64 64 configitem('blackbox', 'dirty',
65 65 default=False,
66 66 )
67 67 configitem('blackbox', 'maxsize',
68 68 default='1 MB',
69 69 )
70 70 configitem('blackbox', 'logsource',
71 71 default=False,
72 72 )
73 73
74 74 lastui = None
75 75
76 76 def wrapui(ui):
77 77 class blackboxui(ui.__class__):
78 78 def __init__(self, src=None):
79 79 super(blackboxui, self).__init__(src)
80 80 if src is None:
81 81 self._partialinit()
82 82 else:
83 83 self._bbfp = getattr(src, '_bbfp', None)
84 84 self._bbinlog = False
85 85 self._bbrepo = getattr(src, '_bbrepo', None)
86 86 self._bbvfs = getattr(src, '_bbvfs', None)
87 87
88 88 def _partialinit(self):
89 89 if util.safehasattr(self, '_bbvfs'):
90 90 return
91 91 self._bbfp = None
92 92 self._bbinlog = False
93 93 self._bbrepo = None
94 94 self._bbvfs = None
95 95
96 96 def copy(self):
97 97 self._partialinit()
98 98 return self.__class__(self)
99 99
100 100 @util.propertycache
101 101 def track(self):
102 102 return self.configlist('blackbox', 'track', ['*'])
103 103
104 104 def _openlogfile(self):
105 105 def rotate(oldpath, newpath):
106 106 try:
107 107 self._bbvfs.unlink(newpath)
108 108 except OSError as err:
109 109 if err.errno != errno.ENOENT:
110 110 self.debug("warning: cannot remove '%s': %s\n" %
111 111 (newpath, err.strerror))
112 112 try:
113 113 if newpath:
114 114 self._bbvfs.rename(oldpath, newpath)
115 115 except OSError as err:
116 116 if err.errno != errno.ENOENT:
117 117 self.debug("warning: cannot rename '%s' to '%s': %s\n" %
118 118 (newpath, oldpath, err.strerror))
119 119
120 120 maxsize = self.configbytes('blackbox', 'maxsize')
121 121 name = 'blackbox.log'
122 122 if maxsize > 0:
123 123 try:
124 124 st = self._bbvfs.stat(name)
125 125 except OSError:
126 126 pass
127 127 else:
128 128 if st.st_size >= maxsize:
129 129 path = self._bbvfs.join(name)
130 130 maxfiles = self.configint('blackbox', 'maxfiles', 7)
131 131 for i in xrange(maxfiles - 1, 1, -1):
132 132 rotate(oldpath='%s.%d' % (path, i - 1),
133 133 newpath='%s.%d' % (path, i))
134 134 rotate(oldpath=path,
135 135 newpath=maxfiles > 0 and path + '.1')
136 136 return self._bbvfs(name, 'a')
137 137
138 def _bbwrite(self, fmt, *args):
139 self._bbfp.write(fmt % args)
140 self._bbfp.flush()
141
142 138 def log(self, event, *msg, **opts):
143 139 global lastui
144 140 super(blackboxui, self).log(event, *msg, **opts)
145 141 self._partialinit()
146 142
147 143 if not '*' in self.track and not event in self.track:
148 144 return
149 145
150 146 if self._bbfp:
151 147 ui = self
152 148 elif self._bbvfs:
153 149 try:
154 150 self._bbfp = self._openlogfile()
155 151 except (IOError, OSError) as err:
156 152 self.debug('warning: cannot write to blackbox.log: %s\n' %
157 153 err.strerror)
158 154 del self._bbvfs
159 155 self._bbfp = None
160 156 ui = self
161 157 else:
162 158 # certain ui instances exist outside the context of
163 159 # a repo, so just default to the last blackbox that
164 160 # was seen.
165 161 ui = lastui
166 162
167 163 if not ui or not ui._bbfp:
168 164 return
169 165 if not lastui or ui._bbrepo:
170 166 lastui = ui
171 167 if ui._bbinlog:
172 168 # recursion guard
173 169 return
174 170 try:
175 171 ui._bbinlog = True
176 172 default = self.configdate('devel', 'default-date')
177 173 date = util.datestr(default, '%Y/%m/%d %H:%M:%S')
178 174 user = util.getuser()
179 175 pid = '%d' % util.getpid()
180 176 formattedmsg = msg[0] % msg[1:]
181 177 rev = '(unknown)'
182 178 changed = ''
183 179 if ui._bbrepo:
184 180 ctx = ui._bbrepo[None]
185 181 parents = ctx.parents()
186 182 rev = ('+'.join([hex(p.node()) for p in parents]))
187 183 if (ui.configbool('blackbox', 'dirty') and
188 184 ctx.dirty(missing=True, merge=False, branch=False)):
189 185 changed = '+'
190 186 if ui.configbool('blackbox', 'logsource'):
191 187 src = ' [%s]' % event
192 188 else:
193 189 src = ''
194 190 try:
195 ui._bbwrite('%s %s @%s%s (%s)%s> %s',
196 date, user, rev, changed, pid, src, formattedmsg)
191 fp = ui._bbfp
192 fmt = '%s %s @%s%s (%s)%s> %s'
193 args = (date, user, rev, changed, pid, src, formattedmsg)
194 fp.write(fmt % args)
195 fp.flush()
197 196 except IOError as err:
198 197 self.debug('warning: cannot write to blackbox.log: %s\n' %
199 198 err.strerror)
200 199 finally:
201 200 ui._bbinlog = False
202 201
203 202 def setrepo(self, repo):
204 203 self._bbfp = None
205 204 self._bbinlog = False
206 205 self._bbrepo = repo
207 206 self._bbvfs = repo.vfs
208 207
209 208 ui.__class__ = blackboxui
210 209 uimod.ui = blackboxui
211 210
212 211 def uisetup(ui):
213 212 wrapui(ui)
214 213
215 214 def reposetup(ui, repo):
216 215 # During 'hg pull' a httppeer repo is created to represent the remote repo.
217 216 # It doesn't have a .hg directory to put a blackbox in, so we don't do
218 217 # the blackbox setup for it.
219 218 if not repo.local():
220 219 return
221 220
222 221 if util.safehasattr(ui, 'setrepo'):
223 222 ui.setrepo(repo)
224 223 repo._wlockfreeprefix.add('blackbox.log')
225 224
226 225 @command('^blackbox',
227 226 [('l', 'limit', 10, _('the number of events to show')),
228 227 ],
229 228 _('hg blackbox [OPTION]...'))
230 229 def blackbox(ui, repo, *revs, **opts):
231 230 '''view the recent repository events
232 231 '''
233 232
234 233 if not repo.vfs.exists('blackbox.log'):
235 234 return
236 235
237 236 limit = opts.get('limit')
238 237 fp = repo.vfs('blackbox.log', 'r')
239 238 lines = fp.read().split('\n')
240 239
241 240 count = 0
242 241 output = []
243 242 for line in reversed(lines):
244 243 if count >= limit:
245 244 break
246 245
247 246 # count the commands by matching lines like: 2013/01/23 19:13:36 root>
248 247 if re.match('^\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2} .*> .*', line):
249 248 count += 1
250 249 output.append(line)
251 250
252 251 ui.status('\n'.join(reversed(output)))
General Comments 0
You need to be logged in to leave comments. Login now