Advertisement
Guest User

Untitled

a guest
May 21st, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. import logging
  2. import json
  3. import types
  4. from traceback import format_tb
  5. from simplegeneric import generic
  6.  
  7.  
  8. @generic
  9. def encode_log_record(obj):
  10. return repr(obj)
  11.  
  12.  
  13. @encode_log_record.when_type(types.TracebackType)
  14. def encode_log_record_traceback(obj):
  15. return format_tb(obj)
  16.  
  17.  
  18. class LogRecordEncoder(json.JSONEncoder):
  19.  
  20. def default(self, obj):
  21. return encode_log_record(obj)
  22.  
  23.  
  24. class TTYOrJSONStreamHandler(logging.StreamHandler):
  25. """ StreamHandler that use standard when logging to a TTY.
  26.  
  27. JSON logging good for machines but ugly for humans.
  28. We check if logging to a TTY stream and use normal
  29. log formatting. Otherwise we encode the `LogRecord`
  30. in JSON .
  31.  
  32. We also fall back to the JSON encoded LogRecord if the
  33. formatting raises an exception (e.g. wrong arguments).
  34.  
  35. You can set the `force_formatted` variable to
  36. log formatted messages even if logging to non-TTY
  37. (e.g. redirecting stderr).
  38. """
  39.  
  40. force_formatted = False
  41.  
  42. def format(self, record):
  43. try:
  44. formatted = super(TTYOrJSONStreamHandler, self).format(record)
  45. except Exception as exc:
  46. formatted = None
  47. fmt_exc = exc
  48. else:
  49. fmt_exc = None
  50.  
  51. if (self.stream.isatty() or self.force_formatted) and fmt_exc is None:
  52. return formatted
  53. else:
  54. copy = dict(record.__dict__)
  55. if fmt_exc is None:
  56. copy['formatted'] = formatted
  57. else:
  58. copy['fmt_exc'] = fmt_exc
  59. return json.dumps(copy, cls=LogRecordEncoder)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement