Python logger dynamic filename

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

    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
    

    To prevent creating duplicate handlers, care needs to be taken to ensure that myLogger(name) is only called once per name. Usually that means putting myLogger(name) inside

    if __name__ == '__main__':
        log_hm = myLogger('healthmonitor')
    

    of the main script.

提交回复
热议问题