1.日志作用简介
在python使用过程中,好的日志可以提交研发效率,快速定位问题产生的原因。
2.日志模块封装
下面我们对日志模块进行封装,主要是打印出日志发生具体的时间,以及可以动态去传不同的参数,便于不同地方的使用。
封装代码如下:
import os
import logging
current_path = os.path.dirname(__file__) # 获取路径
log_path = os.path.join(current_path, '../logs/log.txt')
class LogUtils:
def __init__(self, log_file_path=log_path):
self.log_file_path = log_file_path
self.logger = logging.getLogger(__name__) # 创建一个日志对象 定义一个名词
self.logger.setLevel(level=logging.INFO) # 设置全局日志基本 debug info worning error
console = logging.StreamHandler() #创建一个控制台输出日志的对象
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
file_log = logging.FileHandler(log_path,)
file_log.setFormatter(formatter)
self.logger.addHandler(console) # 日志对象配置在控制台输出
self.logger.addHandler(file_log) # 日志对象配置在文件中输出
def info(self, message):
self.logger.info(message)
def error(self, message):
self.logger.error(message)
logger = LogUtils()
if __name__ == '__main__':
logger.info('hello')
运行结果如下所示:
2020-05-06 23:11:48,933 - main - INFO - hello
3.logging模块的应用
下面举一个封装浏览器调用的例子,来演示logging模块的应用,代码如下:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from common import config_value
import os
from common.log_utills import logger
current_path = os.path.dirname(__file__)
dri_path = os.path.join(current_path, config_value.config.chrome_path)
class Browser:
def __init__(self, driver_path=dri_path, driver_name=config_value.config.driver_name):
self.__driver_name = driver_name
self.__driver_path = driver_path
def get_driver(self):
if str(self.__driver_name).lower() == 'chrome':
logger.info('初始化浏览器并启动谷歌浏览器')
return self.__get_chrome_driver()
elif str(self.__driver_name).lower() == 'firefox':
logger.info('初始化浏览器并启动火狐浏览器')
return self.__get_firefox_driver()
def __get_chrome_driver(self):
chrome_options = Options()
chrome_options.add_argument('--disable-gpu') # 谷歌文档提到需要加上这个属性来规避bug
chrome_options.add_argument('lang=zh_CN.UTF-8') # 设置默认编码为utf-8
# chrome_options.add_experimental_option('useAutomationExtension', False) # 取消chrome受自动控制提示
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation']) # 取消chrome受自动控制提示
chrome_driver_path = os.path.join(self.__driver_path, 'chromedriver.exe')
driver = webdriver.Chrome(options=chrome_options, executable_path=chrome_driver_path)
return driver
def __get_firefox_driver(self):
firefox_driver_path = os.path.join(self.__driver_path, 'geckodriver.exe')
driver = webdriver.Firefox(executable_path=firefox_driver_path)
return driver
browser = Browser()
if __name__ == '__main__':
browser.get_driver()
运行结果为:
2020-05-06 23:13:58,448 - common.log_utills - INFO - 初始化浏览器并启动谷歌浏览器