python 日志打印模块,输出时间、文件名、行号信息等

python 日志打印模块,输出时间、文件名、行号等信息

通过logging模块来控制日志的输出,相比print直接格式化输出,更加的方便;可以添加更多的日志信息,比如时间、行号、文件信息统一输出;可以通过 setLevel 来统一控制日志的开启与关闭。

下面是参考代码:

#!/usr/bin/env python
# -*-coding:UTF-8-*-
import logging

logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
                    datefmt='%d-%m-%Y:%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 log
29-02-2020:12:41:17,935 INFO     [log.py:12] This is an info log
29-02-2020:12:41:17,935 CRITICAL [log.py:13] This is critical
29-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)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
                    datefmt='%d-%m-%Y:%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 log
29-02-2020:12:36:30,272 INFO     [log.py:18] This is an info log
29-02-2020:12:36:30,272 CRITICAL [log.py:19] This is critical
29-02-2020:12:36:30,272 ERROR    [log.py:20] An error occurred

29-02-2020:12:36:30,273 INFO     [log.py:23] This is an info log
29-02-2020:12:36:30,273 CRITICAL [log.py:24] This is critical
29-02-2020:12:36:30,273 ERROR    [log.py:25] An error occurred
发布了141 篇原创文章 · 获赞 107 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/ternence_hsu/article/details/104572415