loguru icon indicating copy to clipboard operation
loguru copied to clipboard

Include traceback to JSON

Open sky-py opened this issue 1 year ago • 5 comments

Is there any way to add loguru's beautiful traceback (like that when adding backtrace=True, diagnose=True to log) to CUSTOM JSON log?

For example for

from loguru import logger
import json


def json_formatter(record):
    log_object = {
        'timestamp': record['time'].strftime('%Y-%m-%d %H:%M:%S'),
        'level': record['level'].name,
        'message': record['message'],
        **record['extra']
    }

    return json.dumps(log_object, ensure_ascii=False)

def patching(record):
    record['extra']['serialized'] = json_formatter(record)

logger = logger.patch(patching)

logger.add('error.log',
           level='ERROR',
           format='{extra[serialized]}',
           )


@logger.catch
def error():
    x = 10
    y = 0
    z = x / y

error()

getting:

{"timestamp": "2024-10-06 21:15:27", "level": "ERROR", "message": "An error has been caught in function '<module>', process 'MainProcess' (5572), thread 'MainThread' (7948):"}
Traceback (most recent call last):

> File "D:\User\Dropbox\Python\test\test3.py", line 34, in <module>
    error()
    └ <function error at 0x000001FF66294EA0>

  File "D:\User\Dropbox\Python\test\test3.py", line 32, in error
    z = x / y
        │   └ 0
        └ 10

ZeroDivisionError: division by zero

How to include

Traceback (most recent call last):

> File "D:\User\Dropbox\Python\test\test3.py", line 34, in <module>
    error()
    └ <function error at 0x000001FF66294EA0>

  File "D:\User\Dropbox\Python\test\test3.py", line 32, in error
    z = x / y
        │   └ 0
        └ 10

ZeroDivisionError: division by zero

to JSON?

sky-py avatar Oct 06 '24 18:10 sky-py