4

I'm using python's logging library, but I want the debug logs to have a different format than the warning and error logs. Is this possible?

ETA: I want warnings and errors to appear as:

%(levelname)s: %(message)s

but debug statements to appear as

DEBUG: (only Brian cares about this) : %(message)s

all other questions I've seen have been to change the format, but that changes for EVERYTHING.

1

1 Answer 1

1

First of all, double-check if you really need this. A log output with different record formats is prone to be rather hard to read by both humans and machines.
Maybe what you actually need is different formats for different log destinations (console vs file) which will also have different verbosity (the file will have a debug log with additional information).

Now, the way is to use a custom Formatter:

class MultiformatFormatter(logging.Formatter):
    def __init__(self,<args>):
        <...>
    def format(self,record):
        if record.levelno <= logging.DEBUG:
            s=<generate string one way>
        else:
            s=<generate string another way>
        return s
<...>
#for each handler that this should apply to
handler.setFormatter(MultiformatFormatter(<args>))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.