Skip to content

Customize the uncaught exception error message so it JSON #296

@dilzeem

Description

@dilzeem

Hi I have this custom sink that I use to handle exceptions

def log_exception(*args):
    if len(args) == 1:
        e = args[0]
        etype, value, tb = type(e), e, e.__traceback__
    elif len(args) == 3:
        etype, value, tb = args
    else:
        logger.error("Not able to log exception. Wrong number of arguments given. Should either receive 1 argument "
                        "- an exception, or 3 arguments: exc type, exc value and traceback")
        return

    tb_parsed = []
    for filename, lineno, func, text in traceback.extract_tb(tb):
        tb_parsed.append({"filename": filename, "lineno": lineno, "func": func, "text": text})

    logger.exception(
        "Uncaught exception", extra={
            "exception": traceback.format_exception_only(etype, value)[0].strip(),
            "traceback": tb_parsed
        }
    )

logger.remove()
logger.add(sys.stdout, serialize=True, level="INFO")
sys.excepthook = log_exception

It works fine, and catches the error and formats except the error message, but it is not exactly JSON because of the text Record was: . Is there a way to format this logging error or remove that text so that line is JSON as well?

--- Logging error in Loguru Handler #1 ---
Record was: {'elapsed': datetime.timedelta(seconds=1, microseconds=314659), 'exception': (type=None, value=None, traceback=None), 'extra': {'extra': {'exception': "KeyError: 'yes'", 'traceback': [{'filename': '/mnt/c/Users/sivaharan.rajkumar/GoogleDrive/projects/aws_debug/aws_debug/main.py', 'lineno': 39, 'func': '<module>', 'text': "print(some_dict['yes'])"}]}}, 'file': (name='init_logging.py', path='/mnt/c/Users/sivaharan.rajkumar/GoogleDrive/projects/aws_debug/aws_debug/init_logging.py'), 'function': 'log_exception', 'level': (name='ERROR', no=40, icon='❌'), 'line': 26, 'message': 'Uncaught exception', 'module': 'init_logging', 'name': 'init_logging', 'process': (id=6496, name='MainProcess'), 'thread': (id=140600093005632, name='MainThread'), 'time': datetime(2020, 7, 15, 20, 37, 34, 180836, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200), 'CEST'))}
Traceback (most recent call last):
  File "/home/dilzeem/.cache/pypoetry/virtualenvs/aws-debug-ivZo2Zzb-py3.7/lib/python3.7/site-packages/loguru/_handler.py", line 165, in emit
    formatted = self._serialize_record(formatted, record)
  File "/home/dilzeem/.cache/pypoetry/virtualenvs/aws-debug-ivZo2Zzb-py3.7/lib/python3.7/site-packages/loguru/_handler.py", line 231, in _serialize_record
    "type": record["exception"].type.__name__,
AttributeError: 'NoneType' object has no attribute '__name__'
--- End of logging error ---

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions