3

I am trying to remove some information while logging to console but then keep that information while logging to a file

Here's a basic example:

import logging
import sys

class MyFilter(logging.Filter):
    def filter(self, record):
        record.msg = record.msg.replace("test", "")
        return True

logger = logging.getLogger("mylogger")
logger.setLevel(logging.DEBUG)

console = logging.StreamHandler(sys.stdout)
console.setLevel("INFO")
logger.addHandler(console)

logfile = logging.FileHandler("log.txt", 'w')
logfile.setLevel("ERROR")
logger.addHandler(logfile)

filt = MyFilter()
console.addFilter(filt)

logger.info("test one")
logger.error("test two")

What I'd like to see on console is

one
two

and then in the log file

test two

but it's actually just

two

I'm assuming editing the LogRecord is what's causing this. Is there a way of achieving what I want or is what I'm trying to do not possible in this way?

1 Answer 1

3

I think what you need is a logging.Formatter:

class MyFormatter(logging.Formatter):   
    def format(self, record):
       return record.msg.replace("test", "")

#...
console.setFormatter(MyFormatter())
#...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.