简体   繁体   中英

Python: How to override default logging handler?

Suppose I have got a logger like:

logger = logging.getLogger(__name__)

Then I add a file handler to it. I want all logs go to the file and all info and above log to be printed on screen.

I know I should set the level of the file handler to logging.INFO.

However, if I use logger.setLevel(logging.INFO) , then the debug logs won't go to the file. If I use logger.setLevel(logging.DEBUG) , then all debug logs will be printed on screen.

How to solve this problem?

You should use logger.setLevel(logging.DEBUG) on the logger and handler.setLevel(logging.INFO) on the screen handler. That way the logger gets all messages, the file handler gets all messages but the screen or stream handler gets only INFO or higher.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM