Python多个模块日志记录到同一日志文件
我正在开发一个包含多个包的Python库,并且有一个主程序在这些包之外。我设置了一个日志记录器,用来将日志信息输出到标准输出和一个日志文件,这个设置是根据问题在多个模块中使用Python日志记录的建议来做的。当我把主程序(main.py
)放到一个包(mypackage
)里时,一切都按预期工作。然而,如果我在项目的根文件夹中启动主程序,代码就会出错(ConfigParser.NoSectionError: No section: 'formatters'
)。
有没有什么建议的解决方案呢?
下面是一个最小的工作示例:
.
├── logging.conf
├── main.py
├── mypackage
│ ├── __init__.py
│ └── mymodule.py
└── smodels.log
logging.conf
:
[loggers]
keys=root
[handlers]
keys=consoleHandler,fileHandler
[formatters]
keys=consoleFormatter,fileFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler,fileHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=consoleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=fileFormatter
args=('smodels.log',)
[formatter_consoleFormatter]
format=%(asctime)-8s.%(msecs)03d %(levelname)-8s %(name)s:%(lineno)-3s %(message)s
datefmt=%H:%M:%S
[formatter_fileFormatter]
format=%(asctime)-16s %(levelname)-8s %(filename)-s:%(lineno)-3s %(message)s
datefmt=%Y-%m-%d %H:%M
main.py
:
#!/usr/bin/env python
from mypackage import mymodule
import logging
logger = logging.getLogger(__name__)
def main():
logger.debug('This is a debug message.')
logger.info('This is an info message.')
mymodule.test()
if __name__=='__main__':
main()
__init__.py
:
import mymodule
import logging.config
logging.config.fileConfig('../logging.conf',disable_existing_loggers=False)
logger = logging.getLogger(__name__)
mymodule.py
:
import logging
logger = logging.getLogger(__name__)
def test():
logger.debug('Module debug.')
logger.info('Module info.')
1 个回答
4
这个错误提示说 logging.conf
文件无法被读取:
请按照下面的方式更新你的 _init_.py 文件:
import os
import logging.config
# logging.config.fileConfig('../logging.conf', disable_existing_loggers=False)
basepath = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
logging.config.fileConfig('%s/logging.conf' % basepath)
logger = logging.getLogger(__name__)
如果这样能解决你的问题,请告诉我。