log日志介绍

为了方便排查代码出错原因,增加log模块,可根据日志级别调用对应debug、info、warning、error方法

代码

创建log.py

#author:命命

import logging
import time
import os
import sys
from config import globalparam
curPath = os.path.abspath(os.path.dirname(__file__))
Path = os.path.split(curPath)[0]
sys.path.append(Path)

log_path = globalparam.log_path
class Log:
    def __init__(self):
        self.logname = os.path.join(log_path, '{0}.log'.format(time.strftime('%Y-%m-%d-%H-%M-%S')))

    def __printconsole(self, level, message):
        # 创建一个logger
        logger = logging.getLogger()
        logger.setLevel(logging.DEBUG)
        # 创建一个handler,用于写入日志文件
        fh = logging.FileHandler(self.logname,'a',encoding='utf-8')
        fh.setLevel(logging.DEBUG)
        # 再创建一个handler,用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        # 记录一条日志
        if level == 'info':
            logger.info(message)
        elif level == 'debug':
            logger.debug(message)
        elif level == 'warning':
            logger.warning(message)
        elif level == 'error':
            logger.error(message)
        logger.removeHandler(ch)
        logger.removeHandler(fh)
        # 关闭打开的文件
        fh.close()

    def debug(self, message):
        self.__printconsole('debug', message)

    def info(self, message):
        self.__printconsole('info', message)

    def warning(self, message):
        self.__printconsole('warning', message)

    def error(self, message):
        self.__printconsole('error', message)

调用log模块

新建uselog.py

from log import Log

data = "日志"
Log().debug('成功调用:%s' % data)
Log().info('成功调用:%s' % data)
Log().error('成功调用:%s' % data)
Log().warning('成功调用:%s' % data)

详见github: https://github.com/zhangmoumou1/selenium_python

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处

本文链接:http://zhangyanc.club/subject/article/selenium-log/

许可协议:署名-非商业性使用 4.0 国际许可协议