Delgan / loguru

Python logging made (stupidly) simple
MIT License
19.75k stars 695 forks source link

Include traceback to JSON #1217

Open sky-py opened 1 week ago

sky-py commented 1 week ago

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?

Delgan commented 1 week ago

There is no built-in way, but you can use the better_exception library from which the Loguru tracebacks are derived.