python学习自制彩色,自定义格式日志打印制作LLoghelper

python学习自制彩色,自定义格式日志打印LLoghelper

python print(xxx)
打印出来只显示白色黑底,没有时间,路径,不同的控制台颜色,对一个没有错误崩溃的python项目来说这样调试起一些逻辑非常不方便
在这里插入图片描述
目标:
1.带颜色,路径,时间,自定义格式等的
2.把原生的print也重写了,默认让它带有格式

1.导入logging和colorlog支持

import logging
import colorlog

log_format = colorlog.ColoredFormatter(
        "[%(message_log_color)s%(asctime)s %(pathname)s:%(lineno)d%(reset)s] %(log_color)s%(message)s",
        log_colors={
            "DEBUG": "cyan",
            "INFO": "green",
            "WARNING": "yellow",
            "ERROR": "red",
            "CRITICAL": "white,bg_red",
        },
        secondary_log_colors={
            "message": {
                "DEBUG": "blue",
                "INFO": "blue",
                "WARNING": "blue",
                "ERROR": "blue",
                "CRITICAL": "blue",
            },
        },
        reset=True,  # 重置颜色
        style="%",
    )
logging.basicConfig(
            filename='output.log', 
            level=logging.DEBUG, 
            encoding='utf-8',
            format='[%(asctime)s %(pathname)s:%(lineno)d] %(message)s'
            )
log = logging.getLogger()
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_format)
log.addHandler(console_handler)

log.info("This is a test.")
log.warning("This is a warning.")
log.error("This is an error.")
log.critical("This is a critical error.")
log.debug("This is a debug message.")
print("This is a normal message.")

在这里插入图片描述secondary_log_colors

secondary_log_colors 这个可以在内部配置第二种颜色,

"[%(message_log_color)s%(asctime)s %(pathname)s:%(lineno)d%(reset)s] %(log_color)s%(message)s"

这里作为标题时间,路径格式 %(message_log_color)s xxxx......%(reset)s color—reset之间就可以定义不同的颜色显示了

2.print重置格式化

import builtins #print内置
import inspect #inspect.stack()
import sys
from datetime import datetime

builtins 是print 内置
inspect 可以inspect.stack() 追踪错误信息等的
datatime 时间信息

#字符串颜色代码
COLOR_CODES = {
    "red": "\033[31m",
    "green": "\033[32m",
    "yellow": "\033[33m",
    "blue": "\033[34m",
    "magenta": "\033[35m",
    "cyan": "\033[36m",
    "reset": "\033[0m",
} #字符串颜色代码

def my_print(*args, sep=' ', end='\n', file=sys.stdout, flush=False):
    # 获取调用者的栈帧信息
    stack = inspect.stack()
    # 调用者信息在栈中的位置通常是第二个元素(索引为1)
    if len(stack) > 1:
        # 获取调用者的文件名和行号
        caller_frame = stack[1]
        filename = caller_frame.filename
        lineno = caller_frame.lineno
        # 为了简洁,我们只显示文件名和行号的一部分
        filename = filename.split('/')[-1]  # 假设路径是以'/'分隔的
        # 获取当前时间
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        # 将文件路径和行号添加到输出中
        head = (f"[{current_time} {filename}:{lineno}] ",)
        color_head = (f"{COLOR_CODES['blue']}[{current_time} {filename}:{lineno}] {COLOR_CODES['green']}",)
        color_args = color_head + args
        args = head + args

    # 将输出内容转换为字符串
    output = sep.join(map(str, args)) + end
    color_output = sep.join(map(str, color_args)) + end + COLOR_CODES["reset"]

    # 写入到标准输出
    file.write(color_output)
    if flush:
        file.flush()
    # 同时将内容写入到日志文件
    with open("output.log", 'a', encoding='utf-8') as logfile:
        logfile.write(output)

# 保存原始的 print 函数
original_print = builtins.print
# 重写 print 函数
builtins.print = my_print

log.info("This is a test.")
log.warning("This is a warning.")
log.error("This is an error.")
log.critical("This is a critical error.")
log.debug("This is a debug message.")
print("This is a normal message.")

运行结果
在这里插入图片描述看到了自己的颜色配置完成!

3.制作pypi包 pip install LLoghelper

步骤 1: 构建和发布你的包

可以用git bash工具执行

安装打包工具:

如果你还没有安装 setuptools 和 wheel,可以通过以下命令安装:

pip install --upgrade setuptools wheel

创建源码包:

使用 setup.py 创建源码包:

python setup.py sdist bdist_wheel

这将在 dist/ 目录下生成 .tar.gz 和 .whl 文件。

安装 twine:

twine 是一个用于上传 Python 包的工具:

pip install twine

上传到 PyPI:

使用 twine 上传你的包到 PyPI:

twine upload dist/*

你可能需要输入你的 PyPI 用户名和密码。如果你还没有 PyPI 账户,需要先注册一个。

注意:这里需要windows power shell 执行,git bash会卡死

最后测试

pip install LLoghelper

完美收官!

有需要的可以直接
pip install LLoghelper

导入:

from LLoghelper.log_helper import log, logger

还可以设置是否使用log,和print重写:

logger.set_log_enable(True, False) #控制日志log, print 是否可以打印  print=false恢复原样

最新print支持配置颜色

调用方法:
print("This is a test.")
print("This is a critical test.", log_level=logger.CRITICAL)
print("This is a warning test.", log_level=logger.WARNING)
print("This is an error test.", log_level=logger.ERROR)
print("This is a debug test.", log_level=logger.DEBUG)
print("This is a info test.", log_level=logger.INFO)

即可使用!谢谢观赏!

github地址:https://github.com/atgczcl/LLoghelper.git
PyPi地址:https://pypi.org/project/LLoghelper/

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值