Custom log handler and logging.config.fileConfig()

Lowell Alleman lowell at allemansonline.com
Thu May 29 10:53:50 EDT 2008


Is there any reason not to do this assignment in the "myhandler.py"
directly?  This would save a step for each application that needs to
use it.

Starting from your example, it would now look like this:

# -- myhandler.py ---
import logging.handlers

class MySpecialHandler(logging.handlers.RotatingFileHandler):
    def __init__(self, fn):
        logging.handlers.RotatingFileHandler.__init__(self, fn,
           maxBytes=2000, backupCount=3)

# Register handler in the "logging.handlers" namespace
logging.handlers.MySpecialHandler = MySpecialHandler


# -- app.py ---
import logging.handlers, logging.config
import myhandler

logging.config.fileConfig("logging.ini")
...


> Hi Lowell,
>
> I think it's OK to use the logging.handlers namespace to add your
> custom handlers - after all, the handlers namespace is for holding
> handlers other than the basic ones included in "logging". So...
>
> # -- myhandler.py ---
> import logging.handlers
>
> class MySpecialHandler(logging.handlers.RotatingFileHandler):
>    def __init__(self, fn):
>        logging.handlers.RotatingFileHandler.__init__(self, fn,
> maxBytes=2000, backupCount=3)
>
>
> # -- logging.ini ---
> [loggers]
> keys=root
>
> [handlers]
> keys=hand01
>
> [formatters]
> keys=form01
>
> [logger_root]
> level=NOTSET
> handlers=hand01
>
> [handler_hand01]
> class=handlers.MySpecialHandler
> level=NOTSET
> formatter=form01
> args=("rotating.log",)
>
> [formatter_form01]
> format=%(asctime)s %(levelname)s %(message)s
> datefmt=
> class=Formatter
>
> # -- app.py ---
> import logging.handlers, logging.config
> from myhandler import MySpecialHandler
>
> logging.handlers.MySpecialHandler = MySpecialHandler
>
> logging.config.fileConfig("logging.ini")
>
> logger = logging.getLogger("test")
>
> for i in xrange(100):
>    logger.debug("Message no. %d", i)
>
>
> should produce the expected results.
> --
> http://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list