kdubs
kdubs

Reputation: 946

Applying Python logging filter

I created a logging filter for my error messages that sets an environment variable. However, when I apply the filter to my logger it stops printing my error messages to the terminal/writing them to my logging file.

Filter looks like this:

class ErrorFilter(logging.Filter):
  def __init__(self,level):
    self.level = level

  def filter(self,record):
    if record.levelno == self.level:
        os.environ["ERROR_FLAG"] = "True"

Applied like this:

logger     = Utils.getLogger() 
logger.addFilter(ErrorFilter(logging.ERROR))

If I don't apply the filter then I get the error message printed in my terminal and written to a file, but when I add the filter that stops. How do I fix this?

Upvotes: 0

Views: 217

Answers (1)

masnun
masnun

Reputation: 11906

You have to return something from the filter method. If you return 0 like values, it will not log anything. If you return a non zero value, it will log the value.

In your case you did not explicitly return anything so it returns None which is a non zero value - this is why it's not logging anything. You can change it to the following:

class ErrorFilter(logging.Filter):
  def __init__(self,level):
    self.level = level

  def filter(self,record):
    if record.levelno == self.level:
        os.environ["ERROR_FLAG"] = "True"
        return True

Upvotes: 1

Related Questions