Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use fileConfig to configure custom handlers in Python

I'm using a config file to configure my logger in a Python application. This is the file:

[loggers]
keys=root

[logger_root]
level=INFO
handlers=console

[handlers]
keys=console,file_rotating

[handler_console]
class=StreamHandler
level=WARNING
formatter=console
args=(sys.stderr,)

[handler_file_rotating]
class=TimeRotatingFileHandler
level=DEBUG
formatter=file
args=('../logs/twicker.log', 'd', 1, 5)

[formatters]
keys=console,file

[formatter_console]
format=%(levelname)s - %(message)s

[formatter_file]
format=%(asctime)s - %(levelname)s - %(module)s - %(message)s

My problem is with TimeRotatingFileHandler. Everytime I run the app I get the next error:

ImportError: No module named 'TimeRotatingFileHandler'

What I'm doing wrong? I tried also changing class line to class=handlers.TimeRotatingFileHandler but in that case I get the next error:

ImportError: No module named 'handlers'

like image 984
David Moreno García Avatar asked Dec 11 '22 01:12

David Moreno García


1 Answers

The class= is evaluated in the namespace of the logging module, and by default this does not have a binding to handlers. So you could do

import logging, logging.handlers
logging.handlers = logging.handlers

before calling fileConfig(), and then class=handlers.TimedRotatingHandler should work.

like image 121
Vinay Sajip Avatar answered Dec 26 '22 19:12

Vinay Sajip