zoukankan      html  css  js  c++  java
  • 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")
    

      

    人生如修仙,岂是一日间。何时登临顶,上善若水前。
  • 相关阅读:
    为啥负利率国债有人抢着买?因为时代变了
    微增长时代
    U盘插入电脑后图标是灰色的,打开提示“请将磁盘插入驱动器”
    计算shell 脚本的执行时间
    win10系统应用商店打开后无法联网 代码: 0x80131500 的解决办法
    Jetbrains家的软件都可用的激活码-pycharm
    postman中x-www-form-urlencoded与form-data的区别
    升级Gogs版本
    上海对售价超1499元的茅台酒即没收并另处罚款
    提高收入的根本途径
  • 原文地址:https://www.cnblogs.com/f-society/p/13653891.html
Copyright © 2011-2022 走看看