Python logger dynamic filename

前端 未结 3 1884
余生分开走
余生分开走 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:43

    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)
    

提交回复
热议问题