0

In Python, we get both DEBUG and INFO messages when the level is set to DEBUG. And, we do not get DEBUG messages when level is set to INFO.

I want the exact opposite of this. I want only DEBUG messages when level is set to DEBUG. And both INFO and DEBUG messages when level is set to INFO.

All logs should be there in the console.

Any way to achieve this?

3
  • If you are not constrained by an existing codebase, you could switch your use of DEBUG and INFO. Commented Apr 29, 2019 at 9:39
  • @JoshuaFox Switching is not an option. Commented Apr 29, 2019 at 9:45
  • 2
    this is a classic XY problem: why do you need this? it doesn't make sense, what is your original problem? Commented Apr 29, 2019 at 10:13

2 Answers 2

1

Write a custom Handler.

In the emit function, note record.levelname and print or don't print the record accordingly.

   import logging
   class MyHandler(logging.StreamHandler):
     def emit(self, record):     
       if record.levelname=="DEBUG":
         self.stream.write(msg)
         self.stream.write(self.terminator)
         self.flush()

Then use it in the usual way:

logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = MyHandler() 
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
Sign up to request clarification or add additional context in comments.

2 Comments

How is this used?
attach MyHandler as your handler docs.python.org/3/howto/logging-cookbook.html
0

This would log info logs to file and debug logs to console.

import logging
logging.basicConfig(filename='example.log',level=logging.Info)
logging.debug('This message should go to the log file')
logging.info('So should this') 
logging.warning('And this, too')

1 Comment

I cannot use a file. All logs should be in the console.

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.