内置模块二——logging

本文详细介绍了Python中logging模块的使用方法,包括基本配置、logger对象的高级配置,以及如何通过不同级别的日志来记录程序运行状态。适用于初学者及需要深入理解日志管理的开发者。

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

主要使用对象配置,简单配置了解
#logging 日志
import logging

#Part1 简单配置
logging.basicConfig(level=logging.DEBUG,#打印级别
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%y-%m-%d %H:%M:%S',
filename='test.log',
filemode='w'
)
logging.debug('debug日志')
# logging.info('info日志')
pwd=input('请输入密码')
print(pwd.isdigit())
if pwd.isdigit():
logging.info('info日志')
else:
logging.warning('警告日志')


#Part2 logger对象配置
logger=logging.getLogger()
logger.setLevel(logging.DEBUG)#logger本身有一个过滤,屏幕或者文件有第二个过滤
#先创建一个格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter1 = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

# 创建一个handler,用于写入日志文件
fh=logging.FileHandler('test.log',encoding='utf-8')
fh.setFormatter(formatter)#高可配置化,文件跟格式绑定
logger.addHandler(fh)

fh.setLevel(logging.DEBUG)#二级过滤

# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setFormatter(formatter1)
logger.addHandler(ch)
ch.setLevel(logging.ERROR)#二级过滤


#输出日志
logging.debug('debug message') # 非常细节的日志 —— 排查错误的时候使用
logging.info('info message') # 正常的日志信息
logging.warning('warning message') # 警告
logging.error('error message') # 错误
logging.critical('烟中 message') # 严重错误

转载于:https://www.cnblogs.com/lixiaoxuan/articles/9077735.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值