python logger 动态设置日志名

代码:

import logging

logger = logging.getLogger('')
logger.setLevel(level=logging.INFO)

def setLogName(name):
    handler = logging.FileHandler(name, mode='w')
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', '%a, %d %b %Y %H:%M:%S')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

if __name__ == "__main__":
    setLogName('/Users/test/test_log.txt')
    logger.info("start func111")
    logger.info("start func222")
    logger.info("start func333")

结果:

cat test_log.txt 

Tue, 12 Mar 2019 18:44:53 log.py[line:32] INFO start func111

Tue, 12 Mar 2019 18:44:53 log.py[line:33] INFO start func222

Tue, 12 Mar 2019 18:44:53 log.py[line:34] INFO start func333

 

posted @ 2019-03-12 18:48  声声慢43  阅读(1471)  评论(0编辑  收藏  举报