# !/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')
python自定义控制台输出记录的格式和等级
最新推荐文章于 2024-09-25 09:59:34 发布
这是一个使用Python编写的日志打印函数,结合了datetime模块和colorama库,可以根据日志级别显示不同颜色。函数自动检测输入值中的错误、警告、信息和成功标志,并相应地设置颜色。示例中展示了如何使用不同级别的日志消息。
摘要由CSDN通过智能技术生成