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.:
JavaScript
x
9
1
log_hm = logging.getLogger('healthmonitor')
2
log_hm.info("Testing Log") # Should log to /some/path/healthmonitor.log
3
4
log_sc = logging.getLogger('scripts')
5
log_sc.debug("Testing Scripts") # Should log to /some/path/scripts.log
6
7
log_cr = logging.getLogger('cron')
8
log_cr.info("Testing cron") # Should log to /some/path/cron.log
9
I want to keep it generic and dont want to hardcode all kind of logger names I can have. Is that possible?
Advertisement
Answer
JavaScript
1
20
20
1
import os
2
import logging
3
4
class MyFileHandler(object):
5
6
def __init__(self, dir, logger, handlerFactory, **kw):
7
kw['filename'] = os.path.join(dir, logger.name)
8
self._handler = handlerFactory(**kw)
9
10
def __getattr__(self, n):
11
if hasattr(self._handler, n):
12
return getattr(self._handler, n)
13
raise AttributeError, n
14
15
logger = logging.getLogger('test')
16
logger.setLevel(logging.INFO)
17
handler = MyFileHandler(os.curdir, logger, logging.FileHandler)
18
logger.addHandler(handler)
19
logger.info('hello mylogger')
20