utils.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from functools import wraps
  17. from inspect import getcallargs
  18. _TIME_FUNC_ID = 0
  19. def _log_debug_as_f(f, msg, msg_args):
  20. name = f.__module__
  21. logger = logging.getLogger(name)
  22. if logger.isEnabledFor(logging.DEBUG):
  23. lineno = f.__code__.co_firstlineno
  24. pathname = f.__code__.co_filename
  25. record = logger.makeRecord(
  26. name=name,
  27. level=logging.DEBUG,
  28. fn=pathname,
  29. lno=lineno,
  30. msg=msg,
  31. args=msg_args,
  32. exc_info=None,
  33. )
  34. logger.handle(record)
  35. def log_function(f):
  36. """ Function decorator that logs every call to that function.
  37. """
  38. func_name = f.__name__
  39. @wraps(f)
  40. def wrapped(*args, **kwargs):
  41. name = f.__module__
  42. logger = logging.getLogger(name)
  43. level = logging.DEBUG
  44. if logger.isEnabledFor(level):
  45. bound_args = getcallargs(f, *args, **kwargs)
  46. def format(value):
  47. r = str(value)
  48. if len(r) > 50:
  49. r = r[:50] + "..."
  50. return r
  51. func_args = ["%s=%s" % (k, format(v)) for k, v in bound_args.items()]
  52. msg_args = {"func_name": func_name, "args": ", ".join(func_args)}
  53. _log_debug_as_f(f, "Invoked '%(func_name)s' with args: %(args)s", msg_args)
  54. return f(*args, **kwargs)
  55. wrapped.__name__ = func_name
  56. return wrapped