Why does log.debug() not log when the level is set to logging.DEBUG?

Viewed 65

I was expecting that the following code would output both log lines

import logging

log = logging.getLogger('hello')
log.setLevel(logging.DEBUG)
print(log.getEffectiveLevel())
log.debug('debug log')
log.critical('critical log')

The output is

10
critical log

The level is correctly set to 10 (which corresponds to DEBUG) and despite this log.debug('debug log') does not output anything - why?

3 Answers

You haven't configured the logging system, so it's still using the defaults (level WARN for the root logger).

https://docs.python.org/3/library/logging.html#logging.basicConfig says basicConfig

Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.

Configuring the logging system with basicConfig first will create a handler and formatter that your logger will use:

logging.basicConfig()
log = logging.getLogger('hello')
log.setLevel(logging.DEBUG)
print(log.getEffectiveLevel())
log.debug('debug log')
log.critical('critical log')

Outputs:

10
DEBUG:hello:debug log
CRITICAL:hello:critical log

In Logger.callHandlers, each handler compares the log record's level with its level. If there aren't any handlers, it will use the default of WARNING.

With a StreamHandler it will

sends logging output to streams such as sys.stdout, sys.stderr or any file-like object"

according to the documentation

import logging 
import sys

# Initialize Logger and set Level to DEBUG
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# Initialize a Handler to print to stdout
handler = logging.StreamHandler(sys.stdout)

# Format Handler output
logFormatter = logging.Formatter(
    "%(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p"
)
handler.setFormatter(logFormatter)

# Set Handler Level to DEBUG
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.debug('Debug Info')
>>> 09/19/2020 09:01:00 PM Debug Info

You need to add stream handler

import logging

log = logging.getLogger('hello')
log.setLevel(logging.DEBUG)

# # Create a file handler to store the logs
file_handler = logging.FileHandler('test.log')
log.addHandler(file_handler)

# # Send output to terminal
stream_handler = logging.StreamHandler()
log.addHandler(stream_handler)

log.debug('debug log')
Related