Search code examples
pythonloggingstring-formattingpython-logging

Can Python's logging format be modified depending on the message log level?


I'm using Python's logging mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."

For example:

  logger.error("Running cmd failed")
  logger.info("Running cmd passed")

In this example, I would like the format of the error to be printed differently:

# error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed

Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.


Solution

  • Yes, you can do this by having a custom Formatter class:

    class MyFormatter(logging.Formatter):
        def format(self, record):
            #compute s according to record.levelno
            #for example, by setting self._fmt
            #according to the levelno, then calling
            #the superclass to do the actual formatting
            return s
    

    Then attach a MyFormatter instance to your handlers.