Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logger dynamic filename

Tags:

python

logging

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?

like image 543
sharjeel Avatar asked May 02 '10 16:05

sharjeel


1 Answers

The approach used in the above solution is correct, but that has issue of adding duplicate handlers when called more than once. Here is the improved version.

import os
def getLogger(name):
    # logger.getLogger returns the cached logger when called multiple times
    # logger.Logger created a new one every time and that avoids adding
    # duplicate handlers 
    logger = logging.Logger(name)
    logger.setLevel(logging.DEBUG)
    handler = logging.FileHandler(os.path.join('/some/path/', name + '.log'), 'a')
    logger.addHandler(handler)
    return logger

def test(i):
  log_hm = getLogger('healthmonitor')
  log_hm.info("Testing Log %s", i) # Should log to /some/path/healthmonitor.log

test(1)
test(2)
like image 134
Anand Chitipothu Avatar answered Sep 16 '22 12:09

Anand Chitipothu