logging.warn() add stacktrace

There are several logging.warn('....') calls in the legacy code base I am working on today.

I want to understand the log output better. Up to now logging.warn() does emit one line. But this single line is not enough to understand the context.

I would like to see the stacktrace of the interpreter.

Since there are a lot of logging.warn('....') lines in my code, I would like to leave them like they are and only modify the configuration of the logging.

How can I add the interpreter stacktrace to every warn() or error() call automatically?

I know that logging.exception("message") shows the stacktrace, but I would like to leave the logging.warn() lines untouched.

Answer

it is trivial if you accept to add a log handler:

import logging
import traceback


class WarnWithStackHandler(logging.StreamHandler):
    def emit(self, record):
        if record.levelno == logging.WARNING:
            stack = traceback.extract_stack()
            # skip logging internal stacks
            stack = stack[:-7]
            for line in traceback.format_list(stack):
                print(line, end='')
        super().emit(record)

Leave a Reply

Your email address will not be published. Required fields are marked *