uhoh
uhoh

Reputation: 3745

python logging.config not available?

In the tutorial Good logging practice in Python the main module looks for logging.config but my python 2.7 installations don't show that when I use dir(logging) and when I try to run this example I get:

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 certainly shows up in some documentation so it's not a mistake. Why doesn't it show up in any of my python 2.7 installations (when I type dir(logging) including my anaconda from last year, and how can I get this example to work?

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=

Upvotes: 9

Views: 9805

Answers (1)

salparadise
salparadise

Reputation: 5805

You need to import the module itself not just logging:

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

Why?

It looks like it is not a module included when you import the package, since it is not a namespace of __init__.py in the logging package, however it is in the directory, hence you can still import it explicitly:

> 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

Upvotes: 16

Related Questions