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")
    

      

    人生如修仙,岂是一日间。何时登临顶,上善若水前。
  • 相关阅读:
    转 webpack 插件 svg-sprite-loader
    form-data与x-www-form-urlencoded的区别【转】
    nginx echo 高级语法 echo_location【转】
    占位【转】
    gocron在linux环境下安装及设置开机启动【转】
    AES加密2【转】
    Redis的KEYS命令引起宕机事件【纯转】
    Java四种锁及分布式锁的初解【纯转】
    java转发二进制图片流【原】
    SpringBoot整合Redis及Redis工具类撰写【纯转】
  • 原文地址:https://www.cnblogs.com/f-society/p/13653891.html
Copyright © 2011-2022 走看看