How to list all existing loggers using python.logging module

后端 未结 2 1154
离开以前
离开以前 2020-12-23 15:44

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

相关标签:
2条回答
  • 2020-12-23 16:23

    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.

    0 讨论(0)
  • 2020-12-23 16:49

    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

    0 讨论(0)
提交回复
热议问题