python 日志模块的使用

在日常开发中,日志的输出有助于了解测试任务的执行状态。python提供了日志模块logging。

废话不多说,直接上代码。

MyLogger.py

#! /usr/bin/env python3
# -*- coding:UTF-8 -*-
import logging
import os
import time
# from colorama import Fore, Style


class TestingLogger(object):
    def __init__(self, home, name=""):
        self.home = home
        self.name = name
        # 创建一个handler,用于写入日志文件
        self.time_style = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
        self.basedir = os.path.split(os.path.realpath(__file__))[0]
        log_home = self.basedir + os.sep + self.home + os.sep
        # 创建一个logger
        self.logger = logging.getLogger(self.time_style + self.name + '.log')
        # 设置Log等级总开关
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(self.log_name, mode='w', encoding='utf-8')
        # 输出到file的log等级的开关
        fh.setLevel(logging.DEBUG)
        # 同时在控制台输出的内容
        ch = logging.StreamHandler()
        # 输出到console的log等级的开关
        # ch.setLevel(logging.WARNING)
        ch.setLevel(logging.DEBUG)
        # 定义handler的输出格式
        # formatter = logging.Formatter('%(asctime)s - %(filename)s - %(funcName)s - %(message)s')
        # formatter_fh = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
        formatter_fh = logging.Formatter("%(asctime)s - %(levelname)s: %(message)s")
        formatter_ch = logging.Formatter("%(message)s")
        fh.setFormatter(formatter_fh)
        ch.setFormatter(formatter_ch)
        # 第四步,将logger添加到handler里面
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)

    def debug(self, msg):
        """
        定义输出的颜色debug--white,info--green,warning/error/critical--red
        :param msg: 输出的log文字
        :return:
        """
        # self.logger.debug(Fore.WHITE + str(msg) + Style.RESET_ALL)
        if isinstance(msg, list):
            msg = "".join(msg)
        self.logger.debug(str(msg))

    def info(self, msg):
        # self.logger.info(Fore.GREEN + str(msg) + Style.RESET_ALL)
        if isinstance(msg, list):
            msg = "".join(msg)
        self.logger.info(str(msg))

    def warning(self, msg):
        # self.logger.warning(Fore.RED + str(msg) + Style.RESET_ALL)
        if isinstance(msg, list):
            msg = "".join(msg)
        self.logger.warning(str(msg))

    def error(self, msg):
        # self.logger.error(Fore.RED + str(msg) + Style.RESET_ALL)
        if isinstance(msg, list):
            msg = "".join(msg)
        self.logger.error(str(msg))

    def critical(self, msg):
        # self.logger.critical(Fore.RED + str(msg) + Style.RESET_ALL)
        if isinstance(msg, list):
            msg = "".join(msg)
        self.logger.critical(str(msg))


if __name__ == '__main__':
    mew = TestingLogger("log", "Test_")
    mew.debug('this is a logger debug message')
    mew.info('this is a logger info message')
    mew.warning('this is a logger warning message')
    mew.error('this is a logger error message')
    mew.critical('this is a logger critical message')

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值