Python记录StreamHandler不会从模块记录日志

时间:2018-11-30 19:17:02

标签: python logging

我有一个非常简单的结构。但是我的两个日志处理程序中只有一个正在从我的模块中进行日志记录:

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()

模块

#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")

我跑步时得到:

shows in file and in stdout

我期望:

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

有人告诉我我做错了吗?

1 个答案:

答案 0 :(得分:1)

hoefling完美地解释了为什么以及如何解决。谢谢!

  

在program.py中,您正在配置logging.getLogger(名称)。这将仅影响名为program.py的记录器,因此仅影响program.py本身内的记录。 module1.py中的logging.getLogger( name )将返回一个名为module1.py的记录器,不受program.py中配置的影响。修复非常简单-替换logging.getLogger( > name ),并在program.py中带有logging.getLogger()。这将改为配置根记录器。   hoe脚