/usr/share/pyshared/mvpa/base/verbosity.py is in python-mvpa 0.4.8-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the PyMVPA package for the
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Verbose output and debugging facility
Examples:
from verbosity import verbose, debug; debug.active = [1,2,3]; debug(1, "blah")
"""
__docformat__ = 'restructuredtext'
from sys import stdout, stderr
# GOALS
# any logger should be able
# to log into a file or stdout/stderr
# provide ability to log with/without a new line at the end
#
# debug logger should be able
# to log sets of debug statements
# add/remove debug setid items
# give verbose description about registered debugset items
class Logger(object):
"""
Base class to provide logging
"""
def __init__(self, handlers=None):
"""Initialize the logger with a set of handlers to use for output
Each hanlder must have write() method implemented
"""
if handlers == None:
handlers = [stdout]
self.__close_handlers = []
self.__handlers = [] # pylint friendliness
self._setHandlers(handlers)
self.__lfprev = True
self.__crprev = 0 # number of symbols in previous cr-ed
def __del__(self):
self._closeOpenedHandlers()
def _setHandlers(self, handlers):
"""Set list of handlers for the log.
A handler can be opened files, stdout, stderr, or a string, which
will be considered a filename to be opened for writing
"""
handlers_ = []
self._closeOpenedHandlers()
for handler in handlers:
if isinstance(handler, basestring):
try:
handler = {'stdout' : stdout,
'stderr' : stderr}[handler.lower()]
except:
try:
handler = open(handler, 'w')
self.__close_handlers.append(handler)
except:
raise RuntimeError, \
"Cannot open file %s for writing by the logger" \
% handler
handlers_.append(handler)
self.__handlers = handlers_
def _closeOpenedHandlers(self):
"""Close opened handlers (such as opened logfiles
"""
for handler in self.__close_handlers:
handler.close()
def _getHandlers(self):
"""Return active handlers
"""
return self.__handlers
def __call__(self, msg, lf=True, cr=False, *args, **kwargs):
"""
Write msg to each of the handlers.
It can append a newline (lf = Line Feed) or return
to the beginning before output and to take care about
cleaning previous message if present
it appends a newline (lf = Line Feed) since most commonly each
call is a separate message
"""
if kwargs.has_key('msgargs'):
msg = msg % kwargs['msgargs']
if cr:
msg_ = ""
if self.__crprev > 0:
# wipe out older line to make sure to see no ghosts
msg_ = "\r%s" % (" "*self.__crprev)
msg_ += "\r" + msg
self.__crprev = len(msg)
msg = msg_
# since it makes no sense this days for cr and lf,
# override lf
lf = False
else:
self.__crprev += len(msg)
if lf:
msg = msg + "\n"
self.__crprev = 0 # nothing to clear
for handler in self.__handlers:
try:
handler.write(msg)
except:
print "Failed writing on handler %s" % handler
raise
try:
handler.flush()
except:
# it might be not implemented..
pass
self.__lfprev = lf
handlers = property(fget=_getHandlers, fset=_setHandlers)
lfprev = property(fget=lambda self:self.__lfprev)
class LevelLogger(Logger):
"""
Logger which prints based on level -- ie everything which is smaller
than specified level
"""
def __init__(self, level=0, indent=" ", *args, **kwargs):
"""Define level logger.
It is defined by
`level`, int: to which messages are reported
`indent`, string: symbol used to indent
"""
Logger.__init__(self, *args, **kwargs)
self.__level = level # damn pylint ;-)
self.__indent = indent
self._setLevel(level)
self._setIndent(indent)
def _setLevel(self, level):
"""Set logging level
"""
ilevel = int(level)
if ilevel < 0:
raise ValueError, \
"Negative verbosity levels (got %d) are not supported" \
% ilevel
self.__level = ilevel
def _setIndent(self, indent):
"""Either to indent the lines based on message log level"""
self.__indent = "%s" % indent
def __call__(self, level, msg, *args, **kwargs):
"""
Write msg and indent using self.indent it if it was requested
it appends a newline since most commonly each call is a separate
message
"""
if level <= self.level:
if self.lfprev and self.indent:
# indent if previous line ended with newline
msg = self.indent*level + msg
Logger.__call__(self, msg, *args, **kwargs)
level = property(fget=lambda self: self.__level, fset=_setLevel)
indent = property(fget=lambda self: self.__indent, fset=_setIndent)
class OnceLogger(Logger):
"""
Logger which prints a message for a given ID just once.
It could be used for one-time warning to don't overfill the output
with useless repeatative messages
"""
def __init__(self, *args, **kwargs):
"""Define once logger.
"""
Logger.__init__(self, *args, **kwargs)
self._known = {}
def __call__(self, ident, msg, count=1, *args, **kwargs):
"""
Write `msg` if `ident` occured less than `count` times by now.
"""
if not self._known.has_key(ident):
self._known[ident] = 0
if count < 0 or self._known[ident] < count:
self._known[ident] += 1
Logger.__call__(self, msg, *args, **kwargs)
class SetLogger(Logger):
"""
Logger which prints based on defined sets identified by Id.
"""
def __init__(self, register=None, active=None, printsetid=True,
*args, **kwargs):
if register == None:
register = {}
if active == None:
active = []
Logger.__init__(self, *args, **kwargs)
self.__printsetid = printsetid
self.__registered = register # all "registered" sets descriptions
# which to output... pointless since __registered
self._setActive(active)
self._setPrintsetid(printsetid)
def _setActive(self, active):
"""Set active logging set
"""
# just unique entries... we could have simply stored Set I guess,
# but then smth like debug.active += ["BLAH"] would not work
from mvpa.base import verbose
self.__active = []
registered_keys = self.__registered.keys()
for item in list(set(active)):
if item == '':
continue
if isinstance(item, basestring):
if item in ['?', 'list', 'help']:
self.print_registered(detailed=(item != '?'))
raise SystemExit(0)
if item.upper() == "ALL":
verbose(2, "Enabling all registered debug handlers")
self.__active = registered_keys
break
# try to match item as it is regexp
regexp_str = "^%s$" % item
try:
regexp = re.compile(regexp_str)
except:
raise ValueError, \
"Unable to create regular expression out of %s" % item
matching_keys = filter(regexp.match, registered_keys)
toactivate = matching_keys
if len(toactivate) == 0:
ids = self.registered.keys()
ids.sort()
raise ValueError, \
"Unknown debug ID '%s' was asked to become active," \
" or regular expression '%s' did not get any match" \
" among known ids: %s" \
% (item, regexp_str, ids)
else:
toactivate = [item]
# Lets check if asked items are known
for item_ in toactivate:
if not (item_ in registered_keys):
raise ValueError, \
"Unknown debug ID %s was asked to become active" \
% item_
self.__active += toactivate
self.__active = list(set(self.__active)) # select just unique ones
self.__maxstrlength = max([len(str(x)) for x in self.__active] + [0])
if len(self.__active):
verbose(2, "Enabling debug handlers: %s" % `self.__active`)
def _setPrintsetid(self, printsetid):
"""Either to print set Id at each line"""
self.__printsetid = printsetid
def __call__(self, setid, msg, *args, **kwargs):
"""
Write msg
It appends a newline since most commonly each call is a separate
message
"""
if setid in self.__active:
if len(msg)>0 and self.__printsetid:
msg = "[%%-%ds] " % self.__maxstrlength % (setid) + msg
Logger.__call__(self, msg, *args, **kwargs)
def register(self, setid, description):
""" "Register" a new setid with a given description for easy finding
"""
if self.__registered.has_key(setid):
raise ValueError, \
"Setid %s is already known with description '%s'" % \
( `setid`, self.__registered[setid] )
self.__registered[setid] = description
def setActiveFromString(self, value):
"""Given a string listing registered(?) setids, make then active
"""
# somewhat evil but works since verbose must be initiated
# by now
self.active = value.split(",")
def print_registered(self, detailed=True):
print "Registered debug entries: ",
kd = self.registered
rks = sorted(kd.keys())
maxl = max([len(k) for k in rks])
if not detailed:
# short list
print ', '.join(rks)
else:
print
for k in rks:
print '%%%ds %%s' % maxl % (k, kd[k])
printsetid = property(fget=lambda self: self.__printsetid, \
fset=_setPrintsetid)
active = property(fget=lambda self: self.__active, fset=_setActive)
registered = property(fget=lambda self: self.__registered)
if __debug__:
import os, re
import traceback
import time
from os import getpid
from os.path import basename, dirname
def parseStatus(field='VmSize'):
"""Return stat information on current process.
Usually it is needed to know where the memory is gone, that is
why VmSize is the default for the field to spit out
TODO: Spit out multiple fields. Use some better way than parsing proc
"""
fd = open('/proc/%d/status' % getpid())
lines = fd.readlines()
fd.close()
match = filter(lambda x:re.match('^%s:'%field, x), lines)[0].strip()
match = re.sub('[ \t]+', ' ', match)
return match
def mbasename(s):
"""Custom function to include directory name if filename is too common
Also strip .py at the end
"""
base = basename(s).rstrip('py').rstrip('.')
if base in ['base', '__init__']:
base = basename(dirname(s)) + '.' + base
return base
class TraceBack(object):
def __init__(self, collide=False):
"""Initialize TrackBack metric
:Parameters:
collide : bool
if True then prefix common with previous invocation gets
replaced with ...
"""
self.__prev = ""
self.__collide = collide
def __call__(self):
ftb = traceback.extract_stack(limit=100)[:-2]
entries = [[mbasename(x[0]), str(x[1])] for x in ftb]
entries = filter(lambda x:x[0] != 'unittest', entries)
# lets make it more consize
entries_out = [entries[0]]
for entry in entries[1:]:
if entry[0] == entries_out[-1][0]:
entries_out[-1][1] += ',%s' % entry[1]
else:
entries_out.append(entry)
sftb = '>'.join(['%s:%s' % (mbasename(x[0]),
x[1]) for x in entries_out])
if self.__collide:
# lets remove part which is common with previous invocation
prev_next = sftb
common_prefix = os.path.commonprefix((self.__prev, sftb))
common_prefix2 = re.sub('>[^>]*$', '', common_prefix)
if common_prefix2 != "":
sftb = '...' + sftb[len(common_prefix2):]
self.__prev = prev_next
return sftb
class RelativeTime(object):
"""Simple helper class to provide relative time it took from previous
invocation"""
def __init__(self, format="%3.3f sec"):
self.__prev = None
self.__format = format
def __call__(self):
dt = 0.0
ct = time.time()
if not self.__prev is None:
dt = ct - self.__prev
self.__prev = ct
return self.__format % dt
class DebugLogger(SetLogger):
"""
Logger for debugging purposes.
Expands SetLogger with ability to print some interesting information
(named Metric... XXX) about current process at each debug printout
"""
_known_metrics = {
'vmem' : lambda : parseStatus(field='VmSize'),
'pid' : lambda : parseStatus(field='Pid'),
'asctime' : time.asctime,
'tb' : TraceBack(),
'tbc' : TraceBack(collide=True),
}
def __init__(self, metrics=None, offsetbydepth=True, *args, **kwargs):
if metrics == None:
metrics = []
SetLogger.__init__(self, *args, **kwargs)
self.__metrics = []
self._offsetbydepth = offsetbydepth
self._reltimer = RelativeTime()
self._known_metrics = DebugLogger._known_metrics
self._known_metrics['reltime'] = self._reltimer
for metric in metrics:
self._registerMetric(metric)
def registerMetric(self, func):
"""Register some metric to report
func can be either a function call or a string which should
correspond to known metrics
"""
if isinstance(func, basestring):
if func in ['all', 'ALL']:
func = self._known_metrics.keys()
if isinstance(func, basestring):
if DebugLogger._known_metrics.has_key(func):
func = DebugLogger._known_metrics[func]
else:
if func in ['?', 'list', 'help']:
print 'Known debug metrics: ', \
', '.join(DebugLogger._known_metrics.keys())
raise SystemExit(0)
else:
raise ValueError, \
"Unknown name %s for metric in DebugLogger" % \
func + " Known metrics are " + \
`DebugLogger._known_metrics.keys()`
elif isinstance(func, list):
self.__metrics = [] # reset
for item in func:
self.registerMetric(item)
return
if not func in self.__metrics:
try:
from mvpa.base import debug
debug("DBG", "Registering metric %s" % func)
self.__metrics.append(func)
except:
pass
def __call__(self, setid, msg, *args, **kwargs):
if not self.registered.has_key(setid):
raise ValueError, "Not registered debug ID %s" % setid
if not setid in self.active:
# don't even compute the metrics, since they might
# be statefull as RelativeTime
return
if len(msg) > 0:
msg_ = ' / '.join([str(x()) for x in self.__metrics])
if len(msg_)>0:
msg_ = "{%s}" % msg_
# determine blank offset using backstacktrace
if self._offsetbydepth:
level = len(traceback.extract_stack())-2
else:
level = 1
if len(msg)>250 and 'DBG' in self.active and not setid.endswith('_TB'):
tb = traceback.extract_stack(limit=2)
msg += " !!!2LONG!!!. From %s" % str(tb[0])
msg = "DBG%s:%s%s" % (msg_, " "*level, msg)
SetLogger.__call__(self, setid, msg, *args, **kwargs)
def _setOffsetByDepth(self, b):
self._offsetbydepth = b
offsetbydepth = property(fget=lambda x:x._offsetbydepth,
fset=_setOffsetByDepth)
metrics = property(fget=lambda x:x.__metrics,
fset=registerMetric)
|