在教程Good logging practice in Python中,主模块查找logging.config
,但我的python 2.7安装未显示当我使用dir(logging)
并尝试运行此示例时,我得到:
Traceback (most recent call last):
File "/Users/your-name-here/logging python/example.py", line 7, in <module>
logging.config.fileConfig('logging.ini')
AttributeError: 'module' object has no attribute 'config'
logging.config
当然出现在某些documentation中,所以这不是一个错误。为什么在我的任何python 2.7安装中都没有显示它(当我键入dir(logging)
时,包括我去年的anaconda,以及如何使该示例正常工作?
main.py:
import logging
# load my module
import my_module
# load the logging configuration
logging.config.fileConfig('logging.ini')
my_module.foo()
bar = my_module.Bar()
bar.bar()
my_module.py:
import logging
def foo():
logger = logging.getLogger(__name__)
logger.info('Hi, foo')
class Bar(object):
def __init__(self, logger=None):
self.logger = logger or logging.getLogger(__name__)
def bar(self):
self.logger.info('Hi, bar')
logging.ini:
[loggers]
keys=root
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
答案 0 :(得分:2)
您需要导入模块本身,而不仅仅是日志记录:
In [1]: import logging
In [2]: 'config' in dir(logging)
Out[2]: False
In [3]: import logging.config
In [4]: 'config' in dir(logging)
Out[4]: True
为什么?
导入软件包时似乎没有包含模块,因为它不是日志记录软件包中__init__.py
的命名空间,但是它在目录中,因此您仍然可以显式导入它:
> pwd
/usr/local/Cellar/python@2/2.7.15/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging
ls -1 *py
__init__.py
config.py
handlers.py