Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import logging
- import json
- import types
- from traceback import format_tb
- from simplegeneric import generic
- @generic
- def encode_log_record(obj):
- return repr(obj)
- @encode_log_record.when_type(types.TracebackType)
- def encode_log_record_traceback(obj):
- return format_tb(obj)
- class LogRecordEncoder(json.JSONEncoder):
- def default(self, obj):
- return encode_log_record(obj)
- class TTYOrJSONStreamHandler(logging.StreamHandler):
- """ StreamHandler that use standard when logging to a TTY.
- JSON logging good for machines but ugly for humans.
- We check if logging to a TTY stream and use normal
- log formatting. Otherwise we encode the `LogRecord`
- in JSON .
- We also fall back to the JSON encoded LogRecord if the
- formatting raises an exception (e.g. wrong arguments).
- You can set the `force_formatted` variable to
- log formatted messages even if logging to non-TTY
- (e.g. redirecting stderr).
- """
- force_formatted = False
- def format(self, record):
- try:
- formatted = super(TTYOrJSONStreamHandler, self).format(record)
- except Exception as exc:
- formatted = None
- fmt_exc = exc
- else:
- fmt_exc = None
- if (self.stream.isatty() or self.force_formatted) and fmt_exc is None:
- return formatted
- else:
- copy = dict(record.__dict__)
- if fmt_exc is None:
- copy['formatted'] = formatted
- else:
- copy['fmt_exc'] = fmt_exc
- return json.dumps(copy, cls=LogRecordEncoder)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement