tags:

views:

146

answers:

2

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?

+3  A: 

How about simply wrap the handler code in a function:

import os
def myLogger(name):
    logger=logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    handler=logging.FileHandler(os.path.join('/some/path/',name+'.log'),'w')
    logger.addHandler(handler)
    return logger

log_hm = myLogger('healthmonitor')
log_hm.info("Testing Log") # Should log to /some/path/healthmonitor.log
unutbu
This is a workable solution but I'm looking for something more Pythonic. Could there be a way to exploit the existing Python logging framework rather than adding a wrapper on top of it?
sharjeel
+2  A: 
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')
mg
Could it be possible to add the handler before the "getLogger" call so that I don't have to add it up everytime I call getLogger?
sharjeel
@sharjeel: Set the handler during initialization and all future calls to `getLogger()` don't need to add an handler. The solution is similar to the ~unutbu's one. In that example `myLogger` should be called only once for file, otherwise you will have strange side effects.
mg
I like this approach. You can also keep a track of the files opened and for a new instance, check if the file is already opened then don't re-open.Though, such kind of science is not required in my case :-)
sharjeel