代码:
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