I want to configure my Python logger in such a way so that each instance of logger should log in a file having the same name as the name of the logger itself.
e.g.:
log_hm = logging.getLogger('healthmonitor') log_hm.info("Testing Log") # Should log to /some/path/healthmonitor.log log_sc = logging.getLogger('scripts') log_sc.debug("Testing Scripts") # Should log to /some/path/scripts.log log_cr = logging.getLogger('cron') log_cr.info("Testing cron") # Should log to /some/path/cron.log
I want to keep it generic and dont want to hardcode all kind of logger names I can have. Is that possible?
Advertisement
Answer
import os import logging class MyFileHandler(object): def __init__(self, dir, logger, handlerFactory, **kw): kw['filename'] = os.path.join(dir, logger.name) self._handler = handlerFactory(**kw) def __getattr__(self, n): if hasattr(self._handler, n): return getattr(self._handler, n) raise AttributeError, n logger = logging.getLogger('test') logger.setLevel(logging.INFO) handler = MyFileHandler(os.curdir, logger, logging.FileHandler) logger.addHandler(handler) logger.info('hello mylogger')