Python教程

【IT之路】python3+selenium2实现UI自动化框架封装之公共类库实现:日志类LogUtils.py

本文主要是介绍【IT之路】python3+selenium2实现UI自动化框架封装之公共类库实现:日志类LogUtils.py,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、思路

从ini配置文件中获取日志文件路径、日志文件名称和日志级别

二、常见要点:

1、从ini文件获取日志配置信息

2、获取日志主体

3、设置日志级别

三、实现代码

logConf.ini

[LOG]
base_path = C:\\Users\\Administrator\\Downloads
log_name = ouput.log
log_level = INFO

 

LogUtils.py

#-*-coding:utf-8-*-
'''
Created on 2021年5月3日

日志工具类

@author: mosorg
'''
import logging  # 引入logging模块
import os
from datetime import datetime
from org.mosorg.common.utils.IniHelper import IniHelper
proDir = os.path.split(os.path.realpath(__file__))[0]
configPath = os.path.join(proDir, "logConf.ini")

'''
config.ini文件格式:
[LOG]
base_path = C:\\Users\\Administrator\\Downloads
log_name = ouput.log
log_level = INFO
'''

class LogHelper(object):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
        iniHelper = IniHelper(configPath)
        iniHelper.select_section("LOG")
        global logPath, resultPath, proDir
        proDir = iniHelper.get_value("base_path")
        resultPath = os.path.join(proDir, "result")
        # 创建result file 如果它不存在
        if not os.path.exists(resultPath):
            os.mkdir(resultPath)
        # defined test result file name by localtime
        logPath = os.path.join(resultPath, str(datetime.now().strftime("%Y%m%d%H%M%S")))
        # create test result file if it doesn't exist
        if not os.path.exists(logPath):
            os.mkdir(logPath)
            
        # defined logger
        self.logger = logging.getLogger()
        # defined log level
        self.log_level = iniHelper.get_value("log_level")
        if self.log_level=="INFO":
            self.logger.setLevel(logging.INFO)
            self.log_level=logging.INFO
        if self.log_level=="DEBUG":
            self.logger.setLevel(logging.DEBUG)
            self.log_level=logging.DEBUG
        if self.log_level=="ERROR":
            self.logger.setLevel(logging.ERROR)
            self.log_level=logging.ERROR
        if self.log_level=="CRITICAL":
            self.logger.setLevel(logging.CRITICAL)
            self.log_level=logging.CRITICAL
        # defined handler
        log_name = iniHelper.get_value("log_name")
        handler = logging.FileHandler(os.path.join(logPath, log_name))
        # defined formatter
        formatter = logging.Formatter('%(asctime)s - %(name)s -%(levelname)s - %(message)s')
        # defined formatter
        handler.setFormatter(formatter)
        # add handler
        self.logger.addHandler(handler)
        

    def log(self,msg):
        self.logger.log(self.log_level, msg)
        
        
#直接实例化LogUtils类,方便调用
logHelper=LogHelper()

#日志工具类的调用
if __name__ == '__main__':
    logHelper.log("日志_ ")

 

这篇关于【IT之路】python3+selenium2实现UI自动化框架封装之公共类库实现:日志类LogUtils.py的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!