python自定义控制台输出记录的格式和等级

这是一个使用Python编写的日志打印函数,结合了datetime模块和colorama库,可以根据日志级别显示不同颜色。函数自动检测输入值中的错误、警告、信息和成功标志,并相应地设置颜色。示例中展示了如何使用不同级别的日志消息。
摘要由CSDN通过智能技术生成

# !/usr/bin/env python
# -*-coding:utf-8 -*-

from datetime import datetime

from colorama import Fore, Style


def pp(*values, sep=' ', end='\n', file=None, color=None, level=None):
time_str = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
str_values = [f'[{time_str}]:']

for value in values:
if level is None and str(value).startswith('[ERROR]'):
level = 'error'
elif level is None and str(value).startswith('[WARNING]'):
level = 'warning'
elif level is None and str(value).startswith('[INFO]'):
level = 'info'
elif level is None and str(value).startswith('[SUCCESS]'):
level = 'success'

if level == 'info':
color = Fore.BLUE
elif level == 'warning':
color = Fore.YELLOW
elif level == 'error':
color = Fore.RED
elif level == 'success':
color = Fore.GREEN

for value in values:
str_values.append(str(value))
string = sep.join(str_values) + end
if color:
string = f'{color}{string}{Style.RESET_ALL}'
if file is None:
print(string)
else:
with open(file, 'a') as f:
f.write(string)


if __name__ == "__main__":
# 自动设置日志级别
pp(level='error')
pp('[WARNING] Be careful!')
pp('[INFO] FYI')
pp(level='success')

pp('Hello', 'World!')
pp('Message')

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值