本文共 2004 字,大约阅读时间需要 6 分钟。
python 日志打印模块,输出时间、文件名、行号等信息
通过logging模块来控制日志的输出,相比print直接格式化输出,更加的方便;可以添加更多的日志信息,比如时间、行号、文件信息统一输出;可以通过 setLevel 来统一控制日志的开启与关闭。
下面是参考代码:
#!/usr/bin/env python# -*-coding:UTF-8-*-import logginglogging.basicConfig(format='%(asctime)s.%(msecs)03d [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s', datefmt='## %Y-%m-%d %H:%M:%S')logging.getLogger().setLevel(logging.DEBUG)logger = logging.getLogger()logger.debug("This is a debug log")logger.info("This is an info log")logger.critical("This is critical")logger.error("An error occurred\n")
输出结果:
29-02-2020:12:41:17,935 DEBUG [log.py:11] This is a debug log29-02-2020:12:41:17,935 INFO [log.py:12] This is an info log29-02-2020:12:41:17,935 CRITICAL [log.py:13] This is critical29-02-2020:12:41:17,935 ERROR [log.py:14] An error occurred
如果在项目中需要设置多个不同的日志输出器,可以参考下面的代码:
#!/usr/bin/env python# -*-coding:UTF-8-*-import logging# 设置输出格式logging.basicConfig(format='%(asctime)s.%(msecs)03d [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s', datefmt='## %Y-%m-%d %H:%M:%S')# 设置日志打印级别logging.getLogger("test").setLevel(logging.DEBUG)# 设置日志输出器的名字,可以在项目中配置多个不同的日志输出器logger = logging.getLogger("test")logging.getLogger("info").setLevel(logging.INFO)logger2 = logging.getLogger("info")logger.debug("This is a debug log")logger.info("This is an info log")logger.critical("This is critical")logger.error("An error occurred\n")logger2.debug("This is a debug log")logger2.info("This is an info log")logger2.critical("This is critical")logger2.error("An error occurred")
输出结果:
29-02-2020:12:36:30,272 DEBUG [log.py:17] This is a debug log29-02-2020:12:36:30,272 INFO [log.py:18] This is an info log29-02-2020:12:36:30,272 CRITICAL [log.py:19] This is critical29-02-2020:12:36:30,272 ERROR [log.py:20] An error occurred29-02-2020:12:36:30,273 INFO [log.py:23] This is an info log29-02-2020:12:36:30,273 CRITICAL [log.py:24] This is critical29-02-2020:12:36:30,273 ERROR [log.py:25] An error occurred
转载地址:http://wqfli.baihongyu.com/