Python logger dynamic filename

前端 未结 3 1840
余生分开走
余生分开走 2021-02-06 01:10

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.:

3条回答
  •  孤独总比滥情好
    2021-02-06 01:51

    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')
    

提交回复
热议问题