3

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?

corvid
  • 10,733
  • 11
  • 61
  • 130

1 Answers1

4

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:

Hope this is what you need.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195