Enable log_method_call to work on static method

Enable the decorator to work on a static method. This also
enables one to see the parameters passed to these methods.

Change-Id: I46c02ac888f00fdd66138b238c7ba1363b1b07a8
Closes-bug: #1559970
This commit is contained in:
Gary Kotton 2016-03-21 02:54:23 -07:00
parent c47a91dbbb
commit ee54eaa4d8
2 changed files with 26 additions and 8 deletions

View File

@ -26,9 +26,6 @@ def _get_full_class_name(cls):
def log_method_call(method):
"""Decorator helping to log method calls.
The decorator is not intended to be used for static methods (which
are just simple functions from Python point of view).
:param method: Method to decorate to be logged.
:type method: method definition
"""
@ -36,12 +33,17 @@ def log_method_call(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
first_arg = args[0]
cls = first_arg if isinstance(first_arg, type) else first_arg.__class__
data = {'class_name': _get_full_class_name(cls),
if args:
first_arg = args[0]
cls = (first_arg if isinstance(first_arg, type)
else first_arg.__class__)
caller = _get_full_class_name(cls)
else:
caller = 'static'
data = {'caller': caller,
'method_name': method.__name__,
'args': args[1:], 'kwargs': kwargs}
log.debug('%(class_name)s method %(method_name)s '
log.debug('%(caller)s method %(method_name)s '
'called with arguments %(args)s %(kwargs)s', data)
return method(*args, **kwargs)
return wrapper

View File

@ -15,6 +15,11 @@ from oslo_log import helpers
from oslotest import base as test_base
@helpers.log_method_call
def _static_method():
pass
class LogHelpersTestCase(test_base.BaseTestCase):
def test_log_decorator(self):
@ -35,7 +40,7 @@ class LogHelpersTestCase(test_base.BaseTestCase):
obj = test_class()
for method_name in ('test_method', 'test_classmethod'):
data = {'class_name': helpers._get_full_class_name(test_class),
data = {'caller': helpers._get_full_class_name(test_class),
'method_name': method_name,
'args': args,
'kwargs': kwargs}
@ -44,3 +49,14 @@ class LogHelpersTestCase(test_base.BaseTestCase):
with mock.patch('logging.Logger.debug') as debug:
method(*args, **kwargs)
debug.assert_called_with(mock.ANY, data)
def test_log_decorator_for_static(self):
'''Test that LOG.debug is called with proper arguments.'''
data = {'caller': 'static',
'method_name': '_static_method',
'args': (),
'kwargs': {}}
with mock.patch('logging.Logger.debug') as debug:
_static_method()
debug.assert_called_with(mock.ANY, data)