Why set logging level for each module won't show logs in my code?

Viewed 53

Some simple codes to illustrate my question:

/src
   -- t1.py
   -- t2.py
   -- test.py

The test.py

import logging
import t1
import t2

def main():
    # I need to set logging level for each module, so can't call logging.basicConfig
    # logging.basicConfig(level=logging.DEBUG)
    t1.foo()
    t2.foo2()

if __name__ == "__main__":
    main()

t1.py

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


def foo():
    logger.info('foo log message')

t2.py

import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


def foo2():
    logger.info('foo2 log message')

When I run python3 test.py I won't get logs. But if I call logging.basicConfig(level=logging.DEBUG) in test.py I will get logs.

So what did I do wrong ?

--- update ---

What I can add to the answer I got is that the root logger's default level is 'WARNING'. So I did not get any output.

1 Answers

logger.setLevel(logging.DEBUG) sets level of messages processable by this logger.

logging.basicConfig(level=logging.DEBUG) does more than that. It creates a handler for the root logger which prints the logging records to stdout.

An example from the cookbook:

console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
Related