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?
How about simply wrap the handler code in a function:
To prevent creating duplicate handlers, care needs to be taken to ensure that
myLogger(name)
is only called once pername
. Usually that means puttingmyLogger(name)
insideof the main script.
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.