Pranjal Doshi
Pranjal Doshi

Reputation: 1260

efficient way to attach multiple handler to single logger

I've multiple handler and I want to attach it to single handler. Is there any efficient way to do this.

logger = logging.getLogger('logger')
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)

summary = logging.FileHandler(filename='text_logger.txt', mode='w')
summary.setLevel(logging.INFO)

overview = logging.FileHandler(filename='overview.log', mode='w')

logger.addHandler(console_handler)
logger.addHandler(summary)
logger.addHandler(overview)

I've to use addHandler multiple times. Is there any better way to do this, something like providing list. I quickly went through doc but didn't find it. I might have missed something.

I am thinking defining dict is an option. But suggestion.

Upvotes: 0

Views: 221

Answers (1)

blues
blues

Reputation: 5185

What addHandler() does is appending the handler to a list in the logger. So if you want to add multiple handlers with a single expression you can do this by extending the list directly: logger.handlers.extend([console_handler, summary, overview])

Be aware that addHandler() explicitly is thread safe, so by bypassing that you are losing this protection.

Upvotes: 1

Related Questions