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

本文详细介绍了Python的logging模块使用方法,包括如何设置日志格式、控制日志级别,以及如何创建多个日志输出器。通过示例代码展示了如何在项目中应用logging模块,以实现更高效的日志管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

下面是参考代码:

#!/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().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)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 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值