Charles R
Charles R

Reputation: 1661

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'

Upvotes: 3

Views: 2515

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99415

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.

Upvotes: 2

Related Questions