Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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=
like image 796
uhoh Avatar asked Sep 01 '18 06:09

uhoh


People also ask

Where is logging setup in Python?

You can configure logging as shown above using the module and class functions or by creating a config file or a dictionary and loading it using fileConfig() or dictConfig() respectively. These are useful in case you want to change your logging configuration in a running application.

What is dictConfig?

dictConfig (config) Takes the logging configuration from a dictionary. The contents of this dictionary are described in Configuration dictionary schema below.


Video Answer


1 Answers

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
like image 51
salparadise Avatar answered Nov 02 '22 04:11

salparadise