lghh
lghh

Reputation: 303

Different messages for different loglevels in python

I would like to output different messages for my loglevels.

For DEBUG and ERROR I would like to have an output like this:

  %(levelname)s %(asctime)s [%(filename)s %(name)s.%(funcName)s - Line %(lineno)s] %(message)s

For INFO and WARN I prefer this format:

%(levelname)s %(asctime)s %(message)s

I have already set up a config file with different handlers for each loglevel, but I get

This is my logging configuration:

[loggers]
keys=root

[handlers]
keys=debugHandler,infoHandler,warnHandler,errorHandler

[formatters]
keys=detailedFormatter,simpleFormatter

[logger_root]
handlers=debugHandler,infoHandler,warnHandler,errorHandler
level=DEBUG

[handler_debugHandler]
class=StreamHandler
level=DEBUG
formatter=detailedFormatter

[handler_infoHandler]
class=StreamHandler
level=INFO
formatter=simpleFormatter

[handler_warnHandler]
class=StreamHandler
level=WARN
formatter=simpleFormatter

[handler_errorHandler]
class=StreamHandler
level=ERROR
formatter=detailedFormatter

[formatter_detailedFormatter]
format=%(levelname)s %(asctime)s [%(filename)s %(name)s.%(funcName)s - Line %(lineno)s] %(message)s

[formatter_simpleFormatter]
format=%(levelname)s %(asctime)s %(message)s

if I have the following sample sequence

logging.debug('debug message')
logging.info('info message')
logging.warning('warn message')
logging.error('error message')

I suspect that the debug handler prints at each level, the info handler prints when info or a level above is called, etc.

Is there a solution that my specific formatters are only applied to a specific level?

Upvotes: 1

Views: 159

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99355

Handlers are supposed to be for specific audiences (e.g. support team, user) and not based on the format you want. For that, you need here to use a custom Formatter set for your handler(s) which uses the format according to the logging level. For example, the following script:

import logging

class LevelBasedFormatter(logging.Formatter):
    def format(self, record):
        if record.levelno in (logging.INFO, logging.WARN):
            self._style._fmt = '%(levelname)-8s %(asctime)s %(message)s'
        else:
            self._style._fmt = '%(levelname)-8s %(asctime)s [%(filename)s %(name)s.%(funcName)s - Line %(lineno)s] %(message)s'
        return super().format(record)

logging.basicConfig(level=logging.DEBUG)
logging.getLogger().handlers[0].setFormatter(LevelBasedFormatter())
logging.debug('debug message')
logging.info('info message')
logging.warning('warn message')
logging.error('error message')

prints

DEBUG    2022-04-26 09:25:41,923 [logtest7.py root.<module> - Line 13] debug message
INFO     2022-04-26 09:25:41,923 info message
WARNING  2022-04-26 09:25:41,923 warn message
ERROR    2022-04-26 09:25:41,923 [logtest7.py root.<module> - Line 16] error message

Upvotes: 2

Related Questions