symcbean
symcbean

Reputation: 48387

Standards for logging abstraction in Python?

I'm a python newbie, and writing a small app which will require logging. I want the app to be portable, allowing other admins to configure its behaviour - particularly logging. The characteristics of the logging lib seem to be controlled by the application code rather than the deployment/environment.

Java has log4j, PHP has PSR-3. Is there something equivalent for Python which would allow the system owner to inject their own logging capability?

Upvotes: 1

Views: 291

Answers (1)

Jonathan Beber
Jonathan Beber

Reputation: 557

The best way, in my opinion, to achieve good flexibility, allowing admins to configure your logging settings is to use this config in a ini file:

[loggers]
keys=root

[handlers]
keys=stream_handler

[formatters]
keys=formatter

[logger_root]
level=DEBUG
handlers=stream_handler

[handler_stream_handler]
class=StreamHandler
level=DEBUG
formatter=formatter
args=(sys.stderr,)

[formatter_formatter]
format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s

After that you can read this configuration in your app:

import logging
from logging.config import fileConfig

fileConfig('logging_config.ini')
logger = logging.getLogger()
logger.debug('your debug message')

You can check more here.

Upvotes: 1

Related Questions