Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set a log to min and max level, as to exclude errors

let's say I wanted to have several handlers, but I did not want the logging.ERROR level messages to show up in any file except logs/error.log

formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s', datefmt='%m/%d %H:%M:%S')

handler = RotatingFileHandler('logs/debug.log', maxBytes=100000, backupCount=1)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)

error_handler = RotatingFileHandler('logs/error.log', maxBytes=100000, backupCount=1)
error_handler.setFormatter(formatter)
error_handler.setLevel(logging.ERROR)

app.logger.addHandler(handler)
app.logger.addHandler(error_handler)

so let's say I wanted handler to handle everything from logging.DEBUG up to and including logging.WARNING, but NOT including logging.ERROR. Is this possible?

like image 998
corvid Avatar asked Nov 27 '25 07:11

corvid


1 Answers

You can specify a custom logging filter to filter out records with a level you don't need:

class LevelFilter(object):
    def __init__(self, level):
        self.level = level

    def filter(self, record):
        return record.levelno != self.level

Then you can add the filter to the handler using addFilter():

handler = RotatingFileHandler('logs/debug.log', maxBytes=100000, backupCount=1)
handler.setLevel(logging.DEBUG)
handler.setFormatter(formatter)
handler.addFilter(LevelFilter(logging.ERROR))

In this case, you wouldn't see messages with ERROR level in debug.log.

Also see:

  • python logging specific level only
  • What is the point of setLevel in a python logging handler?

Hope this is what you need.

like image 186
alecxe Avatar answered Nov 28 '25 21:11

alecxe