Writing in Python. Use formatter with logging.exception ()

I have a logger formatter that currently formats all the usual logging levels into a json string. When I want to view the log, I use a javascript web page that converts json to into a table. Used formatter:

formatter = logging.Formatter(
    '{"datetime":"%(asctime)s","level":"%(levelname)s","app":"%(app_name)s","module":"%(module)s",' +
    '"line":"%(lineno)d","function":"%(funcName)s","msg":"%(msg)s"}'   #<switch2>'
)

It works great. Now I want to log exceptions using logging.exception ().

It seems that logging.exception does not provide dict elements that are in all other levels of logging.

How can I capture the stack trace that logging.exception provides, so I can convert it to a json compatible form that I create for all other log entries? I need logging.exception to grab a stacktrace and put it in the json "msg" element. If logging.exception does not provide other dict elements, such as asctime, level, etc., I can create them myself on the fly.

+4
source share
1 answer

It seems that this is due to logging.exception does not accept the "extra" error (which was fixed in versions 2.7 and 3.2 of the branch).

logging.error(), exc_info=True.

FYI, logging.exception() logging.error() , cpython 2.7 source:

def exception(self, msg, *args, **kwargs):
    """
    Convenience method for logging an ERROR with exception information.
    """
    kwargs['exc_info'] = True
    self.error(msg, *args, **kwargs)

. :

+2

Source: https://habr.com/ru/post/1539793/


All Articles