We work on a python program/library for which we would like to set a logging system. Basically we would like to log either on a terminal either on a file. To do so, we will use the excellent logging package embedded in the standard distribution.
The logging level should be customizable by the user via its Preferences. My problem is how to retrieve one of the handler connected to the logger ? I was thinking about something a bit like this:
import logging
class NullHandler(logging.Handler):
def emit(self,record):
pass
HANDLERS = {}
HANDLERS['console'] = logging.StreamHandler()
HANDLERS['logfile'] = logging.FileHandler('test.log','w')
logging.getLogger().addHandler(NullHandler())
logging.getLogger('console').addHandler(HANDLERS['console'])
logging.getLogger('logfile').addHandler(HANDLERS['logfile'])
def set_log_level(handler, level):
if hanlder not in HANDLERS:
return
HANDLERS[handler].setLevel(level)
def log(message, level, logger=None):
if logger is None:
logger= HANDLERS.keys()
for l in logger:
logging.getLogger(l).log(level, message)
As you can see, my implementation implies the use of the HANDLERS global dictionary to store the instances of the handlers I created. I could not find a better way to do so. In that design, it could be said that as I just plugged one handler per logger, the handlers attribute of my loggers objects should be OK, but I am looking for something more general (i.e. how to do if one day one several handlers are plugged to one of my logger ?)
What do you think about this ?
thank you very much
Eric