Retsam
Retsam

Reputation: 33389

Why am I not receiving log INFO messages in python?

So I'm running the following code from the command line python:

import logging

rootLog = logging.getLogger(__name__)
rootLog.setLevel(logging.INFO)
rootLog.warning("This is a root warning")
rootLog.info("This is root info")
def info():
    log = rootLog.getChild("info")
    log.info("This is info")
    log.warning("This is a warning")
info()    

I'm expecting to see all four log messages on the console, but I'm only seeing the warnings. What is going on? Am I misunderstanding something?

EDIT:

I discovered by adding logging.basicConfig() at the beginning of the script that I'll get the output that I expected. This is strange, because the python documentation on logging states:

The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.

Upvotes: 4

Views: 350

Answers (2)

msw
msw

Reputation: 43487

The bit you quote from the manual is under Module-Level Functions and applies only if the module function

 logging.debug()

is literally called. Since you are calling an instance method with rootLog.info() basicConfig isn't getting called for you and you are probably talking to a null logger. The documentation is kinda confusing there.

Use loggging.basicConfig() and things should work.

Upvotes: 3

Silas Ray
Silas Ray

Reputation: 26150

Ok, I dug through the code in the logging module, and I think I figured it out, at least partially. What you are seeing is happening because what you are calling rootLogger isn't actually the root logger. It is true that if no handlers have been added to the root logger (the true root logger) when you call one of the log methods directly on logging, it calls basicConfig, but calling a log method on an instance of Logger as you are doing here does not actually call basicConfig at all. That's actually irrelevant in this case anyway though. :) I'm not sure where the handler that is getting called here is being created, but I can almost guarantee it's attached to the true root logger. The true root logger is initialized by default to WARNING. Try doing logging.root.setLevel(logging.INFO) and see if you get what you expect. You should also see what you want if you manually attach a logger to your rootLogger.

Upvotes: 4

Related Questions