• python 日志模块


    在自己的项目根路径下新建util包

    util包下面新建两个文件

    log.py

    """操作日志记录
    """
    import time
    from loguru import logger
    from pathlib import Path
    from util.pathutil import Pathutil
    # project_path = Path.cwd().parent
    pathutil = Pathutil()
    project_path = pathutil.rootPath
    log_path = Path(project_path, "log")
    t = time.strftime("%Y_%m_%d")
    
    
    class Loggings:
        __instance = None
        logger.add(f"{log_path}/interface_log_{t}.log", rotation="500MB", encoding="utf-8", enqueue=True,
                   retention="10 days")
    
        def __new__(cls, *args, **kwargs):
            if not cls.__instance:
                cls.__instance = super(Loggings, cls).__new__(cls, *args, **kwargs)
    
            return cls.__instance
    
        def info(self, msg):
            return logger.info(msg)
    
        def debug(self, msg):
            return logger.debug(msg)
    
        def warning(self, msg):
            return logger.warning(msg)
    
        def error(self, msg):
            return logger.error(msg)
    
    
    loggings = Loggings()
    if __name__ == '__main__':
        loggings.info("中文test")
        loggings.debug("中文test")
        loggings.warning("中文test")
        loggings.error("中文test")
    
        logger.info('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings')
        n1 = "cool"
        n2 = [1, 2, 3]
        logger.info(f'If you are using Python {n1}, prefer {n2} of course!')

    pathutil.py

    import sys
    import os
    
    
    class Pathutil(object):
        """路径处理工具类"""
    
        def __init__(self):
            # 判断调试模式
            debug_vars = dict((a, b) for a, b in os.environ.items() if a.find('IPYTHONENABLE') >= 0)
    
            # 根据不同场景获取根目录
            if len(debug_vars) > 0:
                """当前为debug运行时"""
                self.rootPath = sys.path[2]
            elif getattr(sys, 'frozen', False):
                """当前为exe运行时"""
                self.rootPath = os.getcwd()
            else:
                """正常执行"""
                self.rootPath = sys.path[1]
    
            # 替换斜杠
            self.rootPath = self.rootPath.replace("\", "/")
    
        def getPathFromResources(self, fileName):
            """按照文件名拼接资源文件路径"""
            filePath = "%s/resources/%s" % (self.rootPath, fileName)
            return filePath

    使用方式:

    main.py

    from util import log
    log = log.Loggings()
    
    
    if __name__ == '__main__':
        log.info("fafa")
    

      

    人生如修仙,岂是一日间。何时登临顶,上善若水前。
  • 相关阅读:
    【LeetCode-动态规划】编辑代价
    【C++】使用istringstream分割字符串
    【LeetCode-字符串】简化路径
    【LeetCode-字符串】简化路径
    【LeetCode-并查集】朋友圈
    【LeetCode-背包】目标和
    【LeetCode-动态规划】分割等和子集
    The code of method _jspService(HttpServletRequest, HttpServletResponse) is exceeding the 65535 bytes
    【错误解决】本地计算机上的mysql服务启动停止后,某些服务在未由其他服务或程序使用时将自动停止
    MySQL解压版安装配置详解
  • 原文地址:https://www.cnblogs.com/f-society/p/13653891.html
Copyright © 2020-2023  润新知