154

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 of Logger objects?

I searched the python.logging documentation but couldn't find such a method.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
mistiru
  • 2,996
  • 3
  • 11
  • 27

3 Answers3

258

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.

Will Keeling
  • 22,055
  • 4
  • 51
  • 61
  • 15
    In 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! – mistiru Nov 12 '18 at 14:23
  • 12
    A small note here is that root logger is not returned by this snippet. – Dimitar Ivanov Jul 02 '19 at 11:03
  • Anyone 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... – Matt-Mac-Muffin Aug 26 '21 at 15:14
  • Note you can access the manager from ***any*** logger, i.e. `my_logger.manager is logging.root.manager`. From the [source](https://github.com/python/cpython/blob/135098743a0fae0efbcd98e35458e5bc721702e9/Lib/logging/__init__.py#L1358): "There is [under normal circumstances] just one Manager instance ..." – djvg Aug 25 '23 at 07:58
35

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

Jonathan L
  • 9,552
  • 4
  • 49
  • 38
  • 1
    This was what solved it for me: the missing root logger was the source of all the problems I had. – vvvvv Aug 31 '22 at 10:20
5

If you are trying to examine the hierarchy of logging objects, I'd recommend using logging_tree.printout():

import logging_tree

logging_tree.printout()

Or, if you want to have the logging tree accessible to your code:

logging_tree.tree()

See https://pypi.org/project/logging_tree/ for more info.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
stephentgrammer
  • 470
  • 6
  • 16
  • 2
    I would have preferred to do it without depending on a third party library, but thank you for the link :) – mistiru Apr 07 '22 at 14:34