Skip to content

Commit

Permalink
Merge pull request #156 from boegel/fail_and_enhance_raiseException
Browse files Browse the repository at this point in the history
add fail log method, make hardcoded stuff in raiseException easy to redefine for deriving classes
  • Loading branch information
JensTimmerman committed Feb 18, 2015
2 parents eb47bee + e9aaae9 commit 36d7235
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 6 deletions.
21 changes: 16 additions & 5 deletions lib/vsc/utils/fancylogger.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,10 @@ class FancyLogger(logging.getLoggerClass()):
# this attribute can be checked to know if the logger is thread aware
_thread_aware = True

# default class for raiseException method, that can be redefined by deriving loggers
RAISE_EXCEPTION_CLASS = Exception
RAISE_EXCEPTION_LOG_METHOD = lambda c, msg: c.warning(msg)

# method definition as it is in logging, can't change this
def makeRecord(self, name, level, pathname, lineno, msg, args, excinfo, func=None, extra=None):
"""
Expand All @@ -188,12 +192,19 @@ def makeRecord(self, name, level, pathname, lineno, msg, args, excinfo, func=Non
new_msg = msg.encode('utf8', 'replace')
return logrecordcls(name, level, pathname, lineno, new_msg, args, excinfo)

def fail(self, message, *args):
"""Log error message and raise exception."""
formatted_message = message % args
self.RAISE_EXCEPTION_LOG_METHOD(formatted_message)
raise self.RAISE_EXCEPTION_CLASS(formatted_message)

def raiseException(self, message, exception=None, catch=False):
"""
logs an exception (as warning, since it can be caught higher up and handled)
logs message and raises an exception (since it can be caught higher up and handled)
and raises it afterwards
catch: boolean, try to catch raised exception and add relevant info to message
(this will also happen if exception is not specified)
@param exception: subclass of Exception to use for raising
@param catch: boolean, try to catch raised exception and add relevant info to message
(this will also happen if exception is not specified)
"""
fullmessage = message

Expand All @@ -211,9 +222,9 @@ def raiseException(self, message, exception=None, catch=False):
fullmessage += " (%s\n%s)" % (detail, tb_text)

if exception is None:
exception = Exception
exception = self.RAISE_EXCEPTION_CLASS

self.warning(fullmessage)
self.RAISE_EXCEPTION_LOG_METHOD(fullmessage)
raise exception(message)

def deprecated(self, msg, cur_ver, max_ver, depth=2, exception=None, *args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def remove_bdist_rpm_source_file():

PACKAGE = {
'name': 'vsc-base',
'version': '2.0.0',
'version': '2.0.1',
'author': [sdw, jt, ag],
'maintainer': [sdw, jt, ag],
'packages': ['vsc', 'vsc.utils', 'vsc.install'],
Expand Down
56 changes: 56 additions & 0 deletions test/fancylogger.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ def setUp(self):
# disable default ones (with default format)
fancylogger.disableDefaultHandlers()

self.orig_raise_exception_class = fancylogger.FancyLogger.RAISE_EXCEPTION_CLASS
self.orig_raise_exception_method = fancylogger.FancyLogger.RAISE_EXCEPTION_LOG_METHOD

def test_getlevelint(self):
"""Test the getLevelInt"""
DEBUG = fancylogger.getLevelInt('DEBUG')
Expand Down Expand Up @@ -182,6 +185,56 @@ def test_deprecated(self):
txt = open(self.logfn, 'r').read()
self.assertTrue(msgre_warning.search(txt))

def test_fail(self):
"""Test fail log method."""
# truncate the logfile
open(self.logfn, 'w')

logger = fancylogger.getLogger('fail_test')
self.assertErrorRegex(Exception, 'failtest', logger.fail, 'failtest')
self.assertTrue(re.match("^WARNING.*failtest$", open(self.logfn, 'r').read()))
self.assertErrorRegex(Exception, 'failtesttemplatingworkstoo', logger.fail, 'failtest%s', 'templatingworkstoo')

open(self.logfn, 'w')
fancylogger.FancyLogger.RAISE_EXCEPTION_CLASS = KeyError
logger = fancylogger.getLogger('fail_test')
self.assertErrorRegex(KeyError, 'failkeytest', logger.fail, 'failkeytest')
self.assertTrue(re.match("^WARNING.*failkeytest$", open(self.logfn, 'r').read()))

open(self.logfn, 'w')
fancylogger.FancyLogger.RAISE_EXCEPTION_LOG_METHOD = lambda c, msg: c.warning(msg)
logger = fancylogger.getLogger('fail_test')
self.assertErrorRegex(KeyError, 'failkeytestagain', logger.fail, 'failkeytestagain')
self.assertTrue(re.match("^WARNING.*failkeytestagain$", open(self.logfn, 'r').read()))

def test_raiseException(self):
"""Test raiseException log method."""
# truncate the logfile
open(self.logfn, 'w')

def test123(exception, msg):
"""Utility function for testing raiseException."""
try:
raise exception(msg)
except:
logger.raiseException('HIT')

logger = fancylogger.getLogger('fail_test')
self.assertErrorRegex(Exception, 'failtest', test123, Exception, 'failtest')
self.assertTrue(re.match("^WARNING.*HIT.*failtest\n.*in test123.*$", open(self.logfn, 'r').read(), re.M))

open(self.logfn, 'w')
fancylogger.FancyLogger.RAISE_EXCEPTION_CLASS = KeyError
logger = fancylogger.getLogger('fail_test')
self.assertErrorRegex(KeyError, 'failkeytest', test123, KeyError, 'failkeytest')
self.assertTrue(re.match("^WARNING.*HIT.*'failkeytest'\n.*in test123.*$", open(self.logfn, 'r').read(), re.M))

open(self.logfn, 'w')
fancylogger.FancyLogger.RAISE_EXCEPTION_LOG_METHOD = lambda c, msg: c.warning(msg)
logger = fancylogger.getLogger('fail_test')
self.assertErrorRegex(AttributeError, 'attrtest', test123, AttributeError, 'attrtest')
self.assertTrue(re.match("^WARNING.*HIT.*attrtest\n.*in test123.*$", open(self.logfn, 'r').read(), re.M))

def _stream_stdouterr(self, isstdout=True, expect_match=True):
"""Log to stdout or stderror, check stdout or stderror"""
fd, logfn = tempfile.mkstemp()
Expand Down Expand Up @@ -322,6 +375,9 @@ def tearDown(self):
self.handle.close()
os.remove(self.logfn)

fancylogger.FancyLogger.RAISE_EXCEPTION_CLASS = self.orig_raise_exception_class
fancylogger.FancyLogger.RAISE_EXCEPTION_LOG_METHOD = self.orig_raise_exception_method


def suite():
""" returns all the testcases in this module """
Expand Down

0 comments on commit 36d7235

Please sign in to comment.