Drew Aschenbrener
Drew Aschenbrener

Reputation: 357

Python Logging StreamHandler isn't logging from modules

I have a very simple structure. But only one of my two logging handlers is logging from my modules:

program.py, support_module1.py, support_module2.py

#program.py
import support_module1 as SM1
import support_module1 as SM2
log = logging.getLogger(__name__)
logging.basicConfig(
    filename='/logs/TestLog.log',
    filemode='w',
    level='DEBUG',
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[logging.FileHandler(r'/logs/TestLog.log')])
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.INFO)
log.addHandler(stdout_handler)

log.debug("shows in file")
log.info("shows in file and in stdout")
SM1.function1()
SM2.function2()

Modules

#support_module1.py
mod1_log = logging.getLogger(__name__)

function1():
    mod1_log.debug("shows in file")
    mod1_log.info("should show in file and in stdout, but only goes to file")


#support_module2.py
mod2_log = logging.getLogger(__name__)

function2():
    mod2_log.debug("shows in file")
    mod2_log.info("should show in file and in stdout, but only goes to file")

When I run I get:

shows in file and in stdout

I'm expecting:

shows in file and in stdout
should show in file and in stdout, but only goes to file
should show in file and in stdout, but only goes to file

Anyone tell me what i'm doing wrong?

Upvotes: 1

Views: 593

Answers (1)

Drew Aschenbrener
Drew Aschenbrener

Reputation: 357

hoefling pefectly explained why and how to fix. Thank you!

In program.py, you are configuring logging.getLogger(name). This will affect only the logger named program.py and thus only log records inside program.py itself. The logging.getLogger(name) inside module1.py will return a different logger named module1.py which is unaffected by the configuration in program.py The fix is very simple - replace logging.getLogger(name) with logging.getLogger() in program.py. This will configure the root logger instead. -hoefling

Upvotes: 1

Related Questions