# log demo **Published by:** [quantdao.eth](https://paragraph.com/@fanguohui/) **Published on:** 2022-03-04 **URL:** https://paragraph.com/@fanguohui/log-demo ## Content # 记录日志的DEMO import logging import time def initLog(): log = logging.getLogger(__name__) log.setLevel(logging.DEBUG) # 输出到txt formatter = logging.Formatter('[%(asctime)s] %(message)s') handler = logging.FileHandler("log_%s.txt" % time.strftime("%Y-%m-%d %H-%M-%S")) handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) # 输出到控制台 console = logging.StreamHandler() console.setLevel(logging.INFO) # 将输出添加到log log.addHandler(handler) log.addHandler(console) # 返回log return log if __name__ == "__main__": # 实例化 log = initLog() while True: log.info("这里写打印信息,可以同时打印到控制台和日志文档中") time.sleep(5) ## Publication Information - [quantdao.eth](https://paragraph.com/@fanguohui/): Publication homepage - [All Posts](https://paragraph.com/@fanguohui/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@fanguohui): Subscribe to updates - [Twitter](https://twitter.com/kevinguohui): Follow on Twitter