Skip to content

Instantly share code, notes, and snippets.

@jgrgt
Created October 12, 2012 12:17
Show Gist options
  • Save jgrgt/3878937 to your computer and use it in GitHub Desktop.
Save jgrgt/3878937 to your computer and use it in GitHub Desktop.
Pylabs logging Nosetests plugin. Still a WIP!
"""Save at /opt/qbase5/lib/python/site-packages/pylogcapture.py"""
from pylabs import q
from nose.plugins.base import Plugin
from nose.util import ln, safe_str
class PyLogTarget(object):
# TODO: memory management, filtering
enabled = True
def __init__(self, level, filters):
self.level = level
self.filters = filters
self.clear()
def log(self, msg, level=5, tags=''):
if level <= self.level:
self.buffer.append(msg)
def clear(self):
self.buffer = ["Pylogtarget: level=%s filters=%s" % (self.level,
self.filters)]
class LogCapture(Plugin):
"""
Pylabs log capture plugin.
"""
enabled = True
env_opt = 'NOSE_NOPYLOGCAPTURE'
name = 'pylogcapture'
score = 500
#logformat = '%(name)s: %(levelname)s: %(message)s'
#logdatefmt = None
clear = False
filters = ['-nose']
def options(self, parser, env):
"""Register commandline options."""
parser.add_option(
"--nopylogcapture", action="store_false",
default=not env.get(self.env_opt), dest="pylogcapture",
help="Disable pylabs logging capture plugin. "
"Logging configuration will be left intact."
" [NOSE_NOLOGCAPTURE]")
#parser.add_option(
#"--logging-format", action="store", dest="logcapture_format",
#default=env.get('NOSE_LOGFORMAT') or self.logformat,
#metavar="FORMAT",
#help="Specify custom format to print statements. "
#"Uses the same format as used by standard logging handlers."
#" [NOSE_LOGFORMAT]")
#parser.add_option(
#"--logging-datefmt", action="store", dest="logcapture_datefmt",
#default=env.get('NOSE_LOGDATEFMT') or self.logdatefmt,
#metavar="FORMAT",
#help="Specify custom date/time format to print statements. "
#"Uses the same format as used by standard logging handlers."
#" [NOSE_LOGDATEFMT]")
parser.add_option(
"--pylogging-filter", action="store", dest="pylogcapture_filters",
default=env.get('NOSE_LOGFILTER'),
metavar="FILTER",
help="Specify which statements to filter in/out.")
#parser.add_option(
#"--logging-clear-handlers", action="store_true",
#default=False, dest="logcapture_clear",
#help="Clear all other logging handlers")
parser.add_option(
"--pylogging-level", action="store",
default=5, dest="logcapture_level",
help="Set the log level to capture")
def configure(self, options, conf):
"""Configure plugin."""
self.conf = conf
# Disable if explicitly disabled, or if logging is
# configured via logging config file
if not options.pylogcapture:# or conf.pyloggingConfig:
self.enabled = False
#self.logformat = options.logcapture_format
#self.logdatefmt = options.logcapture_datefmt
#self.clear = options.logcapture_clear
self.loglevel = options.logcapture_level
if options.logcapture_filters:
self.filters = options.pylogcapture_filters.split(',')
def setupLoghandler(self):
pass
def begin(self):
"""Set up logging handler before test run begins.
"""
self.start()
def start(self):
self.target = PyLogTarget(level=self.loglevel, filters=self.filters)
q.logger.logTargetAdd(self.target)
self.setupLoghandler()
def end(self):
pass
def beforeTest(self, test):
"""Clear buffers and handlers before test.
"""
self.setupLoghandler()
def afterTest(self, test):
"""Clear buffers after test.
"""
self.target.clear()
def formatFailure(self, test, err):
"""Add captured log messages to failure output.
"""
return self.formatError(test, err)
def formatError(self, test, err):
"""Add captured log messages to error output.
"""
# logic flow copied from Capture.formatError
test.capturedPyLogging = records = self.formatLogRecords()
if not records:
return err
ec, ev, tb = err
return (ec, self.addCaptureToErr(ev, records), tb)
def formatLogRecords(self):
return [safe_str(r) for r in self.target.buffer]
def addCaptureToErr(self, ev, records):
return '\n'.join([safe_str(ev), ln('>> begin captured Pylabs logging <<')] + \
records + \
[ln('>> end captured Pylabs logging <<')])
#!/usr/bin/python
"""
Add this file as /usr/local/bin/qnose
Make sure it's executable
"""
import nose
import sys
from pylabs.InitBaseCore import q
if __name__ == '__main__':
from pylogcapture import LogCapture
nose.main(addplugins=[LogCapture()])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment