在教程Good logging practice in Python主模块查找 logging.config
但是当我使用 dir(logging)
时,我的 python 2.7 安装没有显示当我尝试运行此示例时,我得到:
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 时,我怎样才能让这个示例工作?主要.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()
我的模块.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')
日志记录.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=
最佳答案
您需要导入模块本身,而不仅仅是记录:
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
关于python logging.config 不可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52125707/