python: difference between logging.Logger and logging.getLogger
Asked Answered
E

1

6

Yes, I see python doc says: "Loggers are never instantiated directly, but always through the module-level function logging.getLogger(name)", but I have an issue to debug and want to know the root cause.

here is the example:

#!/usr/bin/python
import logging
logger = logging.getLogger("test")

format = "%(asctime)s [%(levelname)-8s] %(message)s"
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(format, datefmt="%Y-%m-%d %H:%M:%S"))
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.info("test")

Using logging.getLogger("test") here, log message will not be printed.

If I change logging.getLogger("test") to logging.Logger("test"), the log message will be printed.

#!/usr/bin/python
import logging
logger = logging.Logger("test")

format = "%(asctime)s [%(levelname)-8s] %(message)s"
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(format, datefmt="%Y-%m-%d %H:%M:%S"))
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.info("test")

Or we can using logging.getLogger("test") and set logger level to logging.DEBUG.

#!/usr/bin/python
import logging
logger = logging.getLogger("test")

format = "%(asctime)s [%(levelname)-8s] %(message)s"
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(format, datefmt="%Y-%m-%d %H:%M:%S"))
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

logger.info("test")
Eugenol answered 19/11, 2016 at 15:44 Comment(0)
A
5

The method .getLogger("test") is looking for any existing logger configurations for the name "test" while the .Logger("test") is creating a default logger with the name "test" and sets the default log level to 0. If the getLogger method doesn't find a logger class by that name then it will create a basic logger that will have an effective level of 30 (https://docs.python.org/3/library/logging.html#logging-levels) which will ignore your DEBUG message. You can check via logger.getEffectiveLevel() to notice the difference.

Ideally you would create loggers and set them based on the proper naming/configurations instead of accepting the default configuration.

Azeotrope answered 19/11, 2016 at 15:59 Comment(3)
seems that doesn't explain why the message is printed while using Logger ("test") but not getLogger("test"). Both of them get a logging.Logger object with log level 0.Eugenol
See edit, didn't realize a section of it was cut off when I submitted.Azeotrope
Thanks ioneyed, I see the difference after checking logger.getEffectiveLevel(), .Logger("test") won't inherit from any logger, while .getLogger("test") will inherit from the root logger which has default log level == 30.Eugenol

© 2022 - 2024 — McMap. All rights reserved.