How to list all existing loggers using python.logging module
37,116
Solution 1
Loggers are held in a hierarchy by a logging.Manager
instance. You can interrogate the manager
on the root logger for the loggers it knows about.
import logging
loggers = [logging.getLogger(name) for name in logging.root.manager.loggerDict]
Calling getLogger(name)
ensures that any placeholder loggers held by loggerDict
are fully initialized when they are added to the list.
Solution 2
If you want to include RootLogger in the list as well, do something similar to:
import logging
loggers = [logging.getLogger()] # get the root logger
loggers = loggers + [logging.getLogger(name) for name in logging.root.manager.loggerDict]
tested on Python 3.7.4
Related videos on Youtube
Author by
mistiru
Updated on April 07, 2022Comments
-
mistiru about 2 years
Is there a way in Python to get a list of all defined loggers?
I mean, does something exist such as
logging.getAllLoggers()
which would return a list ofLogger
objects?I searched the python.logging documentation but couldn't find such a method.
Thank you in advance.
-
mistiru over 5 yearsIn fact, getting the dict of Logger per name is better than simply a list of Logger alone, so
logging.root.manager.loggerDict
was exactly what I was searching for, thank you! -
Dimitar Ivanov almost 5 yearsA small note here is that root logger is not returned by this snippet.
-
Matt-Mac-Muffin over 2 yearsAnyone has an explanation about why PyCharm's linting warns about this snippet:
Unresolved attribute reference 'manager' for class 'RootLogger'
? I know it can be easily disabled, but still... -
mistiru about 2 yearsI would have preferred to do it without depending on a third party library, but thank you for the link :)