Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Include traceback to JSON #1217

Open
sky-py opened this issue Oct 6, 2024 · 3 comments
Open

Include traceback to JSON #1217

sky-py opened this issue Oct 6, 2024 · 3 comments
Labels
question Further information is requested

Comments

@sky-py
Copy link

sky-py commented Oct 6, 2024

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
Copy link
Owner

Delgan commented Oct 6, 2024

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

@Delgan Delgan added the question Further information is requested label Oct 6, 2024
@dmyersturnbull
Copy link

I find serialization unhelpful without tracebacks, so I took a similar approach to @sky-py. I checked out better_exception (thanks @Delgan) and ended up serializing the tracebacks (as list[dict[...]]).

While this works, the need for patch makes it awkward. It means I need a global logger = loguru_logger.patch(...) and to from myapp.core import logger. It's a little bit of unnecessary coupling.

It's not a big deal, just something I felt worth pointing out. I did add a way to limit the traceback depth (for serialized and non-serialized), per logging statement, which is actually pretty helpful.

@Delgan
Copy link
Owner

Delgan commented Nov 11, 2024

@dmyersturnbull Can you use the patcher attribute of the logger.configure() method maybe?
That would patch the logger globally, avoiding the need for a custom from myapp.core import logger import.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants