loguru进一步封装解决打印日志定位异常问题

2023-08-10 15:17:24 浏览数 (1)

代码语言:javascript复制
import os
import sys
import time
from loguru import logger
import inspect

def creat_time_os():
    creat_time = time.strftime("%Y-%m-%d", time.localtime())

    sys.path.append(os.path.dirname(os.path.abspath(__file__)))

    log_path_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
    logs_path = os.path.join(log_path_dir, "logs", creat_time)
    if os.path.exists(logs_path):
        return logs_path
    else:
        try:
            os.makedirs(logs_path)
        except Exception as e:
            print(e)
        return logs_path


# 提供日志功能
class uru_logger:
    # 去除默认控制台输出
    # logger.remove()

    # 输出日志格式

    def __init__(self):
        logger_format = "{time:YYYY-MM-DD HH:mm:ss,SSS} | {level} | {message}"
        logger.remove()  # 这里是不让他重复打印
        logger.add(sys.stderr,  # 这里是不让他重复打印
                   level="DEBUG",
                   format=logger_format,

                   )
        # 输出到文件,并按天分割和压缩
        logs_path = creat_time_os()
        # 日志文件名:由用例脚本的名称,结合日志保存路径,得到日志文件的绝对路径
        logname = os.path.join(logs_path, sys.argv[0].split('/')[-1].split('.')[0])   '.log'
        logger.add(
            logname,
            encoding="utf-8",
            format=logger_format,
            level="INFO",
            rotation="500MB",
            retention="5 days",
            # colorize=True,
            compression="zip")
        self.creat_time = time.strftime("%Y-%m-%d", time.localtime())
        self.log = logger

    def check_format(self):
        if time.strftime("%Y-%m-%d", time.localtime()) != self.creat_time:
            self.__init__()


uru_logger_log = uru_logger()


def log_info(*args):
    '''
    info log信息
    :param message:
    :return:
    '''
    uru_logger_log.check_format()
    try:
        caller_frame = inspect.currentframe().f_back
        function_name = caller_frame.f_code.co_name
        line_number = caller_frame.f_lineno
        previous_module = caller_frame.f_globals['__name__']
        message_part = args[0] if len(args) == 1 else str(args)
        custom_message = f"{previous_module} | {function_name}:{line_number} | - {message_part}"
        uru_logger_log.log.info(custom_message)
    except:
        uru_logger_log.log.info(args[0] if len(args) == 1 else args)


def log_debug(*args):
    '''
    debug log信息
    :param message:
    :return:
    '''
    uru_logger_log.check_format()
    try:
        caller_frame = inspect.currentframe().f_back
        function_name = caller_frame.f_code.co_name
        line_number = caller_frame.f_lineno
        previous_module = caller_frame.f_globals['__name__']
        message_part = args[0] if len(args) == 1 else str(args)
        custom_message = f"{previous_module} | {function_name}:{line_number} | - {message_part}"
        uru_logger_log.log.debug(custom_message)
    except:
        uru_logger_log.log.debug(args[0] if len(args) == 1 else args)


def log_error(*args):
    '''
    error log信息
    :param message:
    :return:
    '''
    uru_logger_log.check_format()
    try:
        caller_frame = inspect.currentframe().f_back
        function_name = caller_frame.f_code.co_name
        line_number = caller_frame.f_lineno
        previous_module = caller_frame.f_globals['__name__']
        message_part = args[0] if len(args) == 1 else str(args)
        custom_message = f"{previous_module} | {function_name}:{line_number} | - {message_part}"
        uru_logger_log.log.error(custom_message)
    except:
        uru_logger_log.log.error(args[0] if len(args) == 1 else args)

0 人点赞