zoukankan      html  css  js  c++  java
  • python3+requests接口自动化-日志封装

    1.logger.py这个文件放到common目录下,封装日志文件的读取

    2.日志保存到logs文件夹

    3.封装代码

     1 import logging
     2 import os
     3 import time
     4 
     5 
     6 # log_path是日志存放路径地址
     7 get_path = os.path.dirname(os.path.abspath(__file__))
     8 log_path = os.path.join(os.path.dirname(get_path),"log")
     9 
    10 
    11 # 如果不存在这个logs文件夹,就自动创建一个
    12 if not os.path.exists(log_path):os.mkdir(log_path)
    13 
    14 class Log():
    15     def __init__(self):
    16         # 文件的命名
    17         self.logname = os.path.join(log_path,"%s.log"%time.strftime("%Y:%m:%d"))
    18         self.logger = logging.getLogger()
    19         self.logger.setLevel(logging.DEBUG)
    20         # 日志输出格式
    21         self.formatter = logging.Formatter('[%(asctime)s] - %(filename)s] - %(levelname)s: %(message)s')
    22 
    23     def __console(self,level,message):
    24 
    25     # 创建一个FileHandler,用于写到本地
    26         fh = logging.FileHandler(self.logname,"a",encoding='utf-8') # 追加模式
    27         fh.setLevel(logging.DEBUG)
    28         fh.setFormatter(self.formatter)
    29         self.logger.addHandler(fh)
    30 
    31         # 创建一个StreamHandler,用于输出到控制台
    32         ch = logging.StreamHandler()
    33         ch.setLevel(logging.DEBUG)
    34         ch.setFormatter(self.formatter)
    35         self.logger.addHandler(ch)
    36 
    37         if level == "info":
    38             self.logger.info(message)
    39         elif level == "debug":
    40             self.logger.debug(message)
    41         elif level == "warning":
    42             self.logger.warning(message)
    43         elif level == "error":
    44             self.logger.error(message)
    45 
    46         # 这两行代码是为了避免日志输出重复问题
    47         self.logger.removeHandler(ch)
    48         self.logger.removeHandler(fh)
    49 
    50         # 关闭打开的文件
    51         fh.close()
    52 
    53     def debug(self,message):
    54         self.__console("debug",message)
    55 
    56     def info(self,message):
    57         self.__console("info",message)
    58     def warning(self,message):
    59         self.__console("warning",message)
    60     def error(self,message):
    61         self.__console("error",message)
    62 
    63 if __name__ == "__main__":
    64     log = Log()
    65     log.info("--测试开始--")
    66     log.info("操作步骤1,2,3")
    67     log.warning("--测试结束--")
  • 相关阅读:
    06 Python类、对象
    05 Python DNS域名轮询业务监控
    04 Python字符串
    03 Python函数
    02 Python循环
    执行config文件时,config.log中报错xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist, use xcode-select to change
    浏览我的php网页时,出现的都是网页的代码
    php
    [转载]用c写PHP的扩展接口(php5,c++)
    PHP扩展编写示例
  • 原文地址:https://www.cnblogs.com/jayson-0425/p/9809947.html
Copyright © 2011-2022 走看看