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")
vvvvv
  • 25,404
  • 19
  • 49
  • 81
vts
  • 871
  • 3
  • 10
  • 21

1 Answers1

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.

ioneyed
  • 1,052
  • 7
  • 12
  • 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. – vts Nov 19 '16 at 16:23
  • See edit, didn't realize a section of it was cut off when I submitted. – ioneyed Nov 19 '16 at 16:29
  • 1
    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. – vts Nov 19 '16 at 16:46