Replace
logging.basicConfig(filename='child.log')
childLogger = logging.getLogger(__name__)
在你的子模块中:
childLogger = logging.getLogger(__name__)
childLogger.addHandler(logging.FileHandler('child.log'))
或者,或者,使用字典配置 https://docs.python.org/2/library/logging.config.html#logging.config.dictConfig or 文件配置 https://docs.python.org/2/library/logging.config.html#logging.config.fileConfig在一处配置日志记录。
出了什么问题基本配置 https://docs.python.org/2/library/logging.html#logging.basicConfig?来自文档:
如果根记录器已为其配置了处理程序,则此函数不会执行任何操作。
所以基本上,你打电话给basicLogging
在子模块中没有任何效果,因为第一个模块(在父模块中)已经配置了根记录器。并通过设置子记录器的propagate
to false
,子级的日志条目不会转发到根记录器,因此您得到No handlers could be found...
警告。
Edit
只是为了详细说明文件配置 https://docs.python.org/2/library/logging.config.html#logging.config.fileConfig,这提供了很大的灵活性,您可以为您的模块创建一个名为的文件logging.ini
:
[loggers]
keys=root,child
[handlers]
keys=logfile,logfile_child
[formatters]
keys=default
# loggers
[logger_root]
level=INFO
handlers=logfile
[logger_child]
level=INFO
handlers=logfile_child
qualname=child
propagate=0
# handlers
[handler_logfile]
class=FileHandler
formatter=default
args=('parent.log',)
[handler_logfile_child]
class=FileHandler
formatter=default
args=('child.log',)
# formatters
[formatter_default]
format=%(asctime)s [%(module)s:%(lineno)d] %(levelname)s %(message)s
datefmt=
然后,在您的应用程序中的某个地方,您只需要调用fileConfig
:
import logging.config
logging.config.fileConfig('logging.ini')
通过这种方式,您的日志记录可以在一个地方进行配置,这样可以更轻松地添加其他记录器、更改日志级别等。