formatter.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 New Vector 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. import traceback
  17. from io import StringIO
  18. class LogFormatter(logging.Formatter):
  19. """Log formatter which gives more detail for exceptions
  20. This is the same as the standard log formatter, except that when logging
  21. exceptions [typically via log.foo("msg", exc_info=1)], it prints the
  22. sequence that led up to the point at which the exception was caught.
  23. (Normally only stack frames between the point the exception was raised and
  24. where it was caught are logged).
  25. """
  26. def __init__(self, *args, **kwargs):
  27. super(LogFormatter, self).__init__(*args, **kwargs)
  28. def formatException(self, ei):
  29. sio = StringIO()
  30. (typ, val, tb) = ei
  31. # log the stack above the exception capture point if possible, but
  32. # check that we actually have an f_back attribute to work around
  33. # https://twistedmatrix.com/trac/ticket/9305
  34. if tb and hasattr(tb.tb_frame, "f_back"):
  35. sio.write("Capture point (most recent call last):\n")
  36. traceback.print_stack(tb.tb_frame.f_back, None, sio)
  37. traceback.print_exception(typ, val, tb, None, sio)
  38. s = sio.getvalue()
  39. sio.close()
  40. if s[-1:] == "\n":
  41. s = s[:-1]
  42. return s