python logging colorlog

本文介绍了一种Python日志模块的配置方法,通过colorlog和logging模块实现带有颜色的日志输出,并设置不同级别的日志信息。代码展示了如何将日志信息输出到控制台和文件中,包括debug、info、warn、error及critical等不同级别。

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

 1 import logging
 2 LOG_LEVEL = logging.NOTSET
 3 LOGFORMAT = "[%(log_color)s%(levelname)s] [%(log_color)s%(asctime)s] %(log_color)s%(filename)s [line:%(log_color)s%(lineno)d] : %(log_color)s%(message)s%(reset)s"
 4 import colorlog
 5 logging.root.setLevel(LOG_LEVEL)
 6 ############
 7 #此配置是将日志输出到myapp.log
 8 colorlog.basicConfig(format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', filename='myapp.log',
 9                 filemode='w', datefmt='%a, %d %b %Y %H:%M:%S', )
10 ##############
11 formatter = colorlog.ColoredFormatter(LOGFORMAT)
12 stream = logging.StreamHandler()
13 stream.setLevel(LOG_LEVEL)
14 stream.setFormatter(formatter)
15 log = logging.getLogger()
16 log.setLevel(LOG_LEVEL)
17 log.addHandler(stream)
18 log.debug("A quirky message only developers care about")
19 log.info("Curious users might want to know this")
20 log.warn("Something is wrong and any user should be informed")
21 log.error("Serious stuff, this is red for a reason")
22 log.critical("OH NO everything is on fire")
23 #####################################

 

转载于:https://www.cnblogs.com/danny-chen/p/6208666.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值