python logging.config 不可用?

uho*_*hoh 7 python logging python-2.7

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'
Run Code Online (Sandbox Code Playgroud)

logging.config肯定会出现在一些文档中,所以这不是一个错误。为什么它没有出现在我的任何 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()
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

登录.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=
Run Code Online (Sandbox Code Playgroud)

sal*_*ise 12

您需要导入模块本身而不仅仅是日志记录:

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
Run Code Online (Sandbox Code Playgroud)

为什么?

看起来它不是导入包时包含的模块,因为它不是__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
Run Code Online (Sandbox Code Playgroud)