utils.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 inspect
  16. import logging
  17. import time
  18. from functools import wraps
  19. from inspect import getcallargs
  20. _TIME_FUNC_ID = 0
  21. def _log_debug_as_f(f, msg, msg_args):
  22. name = f.__module__
  23. logger = logging.getLogger(name)
  24. if logger.isEnabledFor(logging.DEBUG):
  25. lineno = f.__code__.co_firstlineno
  26. pathname = f.__code__.co_filename
  27. record = logging.LogRecord(
  28. name=name,
  29. level=logging.DEBUG,
  30. pathname=pathname,
  31. lineno=lineno,
  32. msg=msg,
  33. args=msg_args,
  34. exc_info=None,
  35. )
  36. logger.handle(record)
  37. def log_function(f):
  38. """ Function decorator that logs every call to that function.
  39. """
  40. func_name = f.__name__
  41. @wraps(f)
  42. def wrapped(*args, **kwargs):
  43. name = f.__module__
  44. logger = logging.getLogger(name)
  45. level = logging.DEBUG
  46. if logger.isEnabledFor(level):
  47. bound_args = getcallargs(f, *args, **kwargs)
  48. def format(value):
  49. r = str(value)
  50. if len(r) > 50:
  51. r = r[:50] + "..."
  52. return r
  53. func_args = ["%s=%s" % (k, format(v)) for k, v in bound_args.items()]
  54. msg_args = {"func_name": func_name, "args": ", ".join(func_args)}
  55. _log_debug_as_f(f, "Invoked '%(func_name)s' with args: %(args)s", msg_args)
  56. return f(*args, **kwargs)
  57. wrapped.__name__ = func_name
  58. return wrapped
  59. def time_function(f):
  60. func_name = f.__name__
  61. @wraps(f)
  62. def wrapped(*args, **kwargs):
  63. global _TIME_FUNC_ID
  64. id = _TIME_FUNC_ID
  65. _TIME_FUNC_ID += 1
  66. start = time.clock()
  67. try:
  68. _log_debug_as_f(f, "[FUNC START] {%s-%d}", (func_name, id))
  69. r = f(*args, **kwargs)
  70. finally:
  71. end = time.clock()
  72. _log_debug_as_f(
  73. f, "[FUNC END] {%s-%d} %.3f sec", (func_name, id, end - start)
  74. )
  75. return r
  76. return wrapped
  77. def trace_function(f):
  78. func_name = f.__name__
  79. linenum = f.func_code.co_firstlineno
  80. pathname = f.func_code.co_filename
  81. @wraps(f)
  82. def wrapped(*args, **kwargs):
  83. name = f.__module__
  84. logger = logging.getLogger(name)
  85. level = logging.DEBUG
  86. frame = inspect.currentframe()
  87. if frame is None:
  88. raise Exception("Can't get current frame!")
  89. s = frame.f_back
  90. to_print = [
  91. "\t%s:%s %s. Args: args=%s, kwargs=%s"
  92. % (pathname, linenum, func_name, args, kwargs)
  93. ]
  94. while s:
  95. if True or s.f_globals["__name__"].startswith("synapse"):
  96. filename, lineno, function, _, _ = inspect.getframeinfo(s)
  97. args_string = inspect.formatargvalues(*inspect.getargvalues(s))
  98. to_print.append(
  99. "\t%s:%d %s. Args: %s" % (filename, lineno, function, args_string)
  100. )
  101. s = s.f_back
  102. msg = "\nTraceback for %s:\n" % (func_name,) + "\n".join(to_print)
  103. record = logging.LogRecord(
  104. name=name,
  105. level=level,
  106. pathname=pathname,
  107. lineno=lineno,
  108. msg=msg,
  109. args=(),
  110. exc_info=None,
  111. )
  112. logger.handle(record)
  113. return f(*args, **kwargs)
  114. wrapped.__name__ = func_name
  115. return wrapped
  116. def get_previous_frames():
  117. frame = inspect.currentframe()
  118. if frame is None:
  119. raise Exception("Can't get current frame!")
  120. s = frame.f_back.f_back
  121. to_return = []
  122. while s:
  123. if s.f_globals["__name__"].startswith("synapse"):
  124. filename, lineno, function, _, _ = inspect.getframeinfo(s)
  125. args_string = inspect.formatargvalues(*inspect.getargvalues(s))
  126. to_return.append(
  127. "{{ %s:%d %s - Args: %s }}" % (filename, lineno, function, args_string)
  128. )
  129. s = s.f_back
  130. return ", ".join(to_return)
  131. def get_previous_frame(ignore=[]):
  132. frame = inspect.currentframe()
  133. if frame is None:
  134. raise Exception("Can't get current frame!")
  135. s = frame.f_back.f_back
  136. while s:
  137. if s.f_globals["__name__"].startswith("synapse"):
  138. if not any(s.f_globals["__name__"].startswith(ig) for ig in ignore):
  139. filename, lineno, function, _, _ = inspect.getframeinfo(s)
  140. args_string = inspect.formatargvalues(*inspect.getargvalues(s))
  141. return "{{ %s:%d %s - Args: %s }}" % (
  142. filename,
  143. lineno,
  144. function,
  145. args_string,
  146. )
  147. s = s.f_back
  148. return None