Created
August 22, 2017 12:42
-
-
Save dan-passaro/49d4655d38daf5d192d7aa67fff4b327 to your computer and use it in GitHub Desktop.
Verbose Python JSON logging for local dev
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import logging | |
def recursive_dict(obj, converted_objs=()): | |
converted_objs = converted_objs or set() | |
try: | |
attrs = obj.__dict__ | |
except AttributeError: | |
if isinstance(obj, dict): | |
attrs = obj | |
else: | |
return obj | |
converted_objs.add(id(obj)) | |
result = {} | |
for k, v in attrs.items(): | |
if id(v) in converted_objs: | |
result[str(k)] = '<recursive>' | |
else: | |
result[str(k)] = recursive_dict(v, converted_objs) | |
return result | |
class DanFormatter(logging.Formatter): | |
def format(self, record): | |
record.message = record.getMessage() | |
record.asctime = self.formatTime(record, self.datefmt) | |
if record.exc_info: | |
record.exc_text = self.formatException(record.exc_info) | |
flat_objs = recursive_dict(record) | |
return json.dumps(flat_objs, default=str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment