简体   繁体   中英

Python logging.basicConfig set different level for handlers

I have the following code for my logging :

logging.basicConfig(
                    handlers=[
                        logging.FileHandler("log.txt", "w"),
                        logging.StreamHandler()
                    ],
                    format='%(levelname)s - %(asctime)s - %(message)s',
                    datefmt='%H:%M:%S',
                    level=logging.DEBUG)

I would like to set a different level for my 2 handlers. But I realy want to keep it simple, I want to do that with the basicConfig.

Is there a way I can do that ?

I tried that but it failed :

logging.basicConfig(
                    handlers=[
                        logging.FileHandler("log.txt", "w", level=logging.DEBUG),
                        logging.StreamHandler(level=logging.DEBUG)
                    ],
                    format='%(levelname)s - %(asctime)s - %(message)s',
                    datefmt='%H:%M:%S')

TypeError: init () got an unexpected keyword argument 'level'

I presume you're not actually going to use DEBUG in practice for the handler levels, as they would pass through all messages (>= DEBUG ) whether or not you set the level to DEBUG . For higher levels, which I have called level1 and level2 for illustrative purposes, you could do

h1 = logging.FileHandler(...); h1.setLevel(level1)
h2 = logging.StreamHandler(...); h2.setLevel(level2)

and then pass handlers=[h1, h2] to basicConfig .

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