python3:从 logging 库中摘‘零件’另造小轮子 简单日志功能

平时写的一些小程序时,需要日志来记录程序运行的情况,但是python标准库 logging 配置起来比较麻烦,所以自己写个函数实现日志功能。

废话不多说,先上代码:

# encoding:utf-8

from sys import exc_info, _getframe
import time
from traceback import TracebackException


def logger(message: str, level='ERROR'):
    """
    当调用logger时,直接给参数字符串时,会写入文件 log
    当给定 level='ERROR' 参数时,另外还会写入异常产生的轨迹,没有则为 None,建议在 except 中使用
    :param message:可传入异常信息
    :param level:
    :return:
    """
    try:
        if isinstance(message, str):
            time_now = time.strftime('%Y-%m-%d %H:%M:%S')
            year_month = time.strftime('%Y-%m')
            log_name = 'log' + year_month + '.txt'
            with open(log_name, 'a', encoding='utf-8') as temp:
                file_path, func_name, line_no = find_caller()  # 报告日志打印位置
                file_name = str(file_path).split('\\')[-1]
                format_message = "{time} |  {level}  | {file_name}:{func_name}:{line_no} - {message}\n".format(
                    time=time_now, level=level, file_name=file_name,
                    func_name=func_name, line_no=line_no, message=message
                )
                tbe = trace_information()
                if level == 'ERROR':
                    print(format_message, ''.join(tbe.format()), file=temp)
                    print(format_message, ''.join(tbe.format()))
                else:
                    print(format_message, file=temp)
                    print(format_message)
    except Exception as e:
        logger('日志发生异常:' + str(e))


def find_caller():
    """
    Find the stack frame of the caller so that we can note the source
    file name, line number and function name.
    抛出一个异常,通过向上查找的方式,找到调用者的信息
    # f = sys._getframe(1).f_back
    :returns 返回调用者所在的文件名,模块名,行号
    """
    try:
        raise SystemError
    except SystemError:
        # f = exc_info()[2].tb_frame.f_back
        f = _getframe(1).f_back
        return f.f_code.co_filename, f.f_code.co_name, f.f_lineno


def trace_information():
    """
    获取异常时的栈轨迹
    :return:
    """
    exc_type, exc_value, exc_tb = exc_info()
    tbe = TracebackException(
        exc_type, exc_value, exc_tb,
    )
    return tbe

其中的函数 find_caller 和 trace_information 是从 logging 源代码中摘抄出来的,用于获取调用者的位置 以及 发生异常时 的异常轨迹。

输出在日志文件和控制台的结果如下图,可以根据实际情况增加或修改功能。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值