Python日志模块
Posted 帅瓶子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python日志模块相关的知识,希望对你有一定的参考价值。
做自动化的时候,我们需要给框架配上日志,出错的时候方便我们查看。
例子:
import logging from Agin_Project.unittest_again.common.file_path import FilePath class My_log: def conf_log(self,level,msg): log = logging.getLogger("test_log") #创建一个日志收集器 log.setLevel(level) #设置日志的级别 # 日志的输出格式 formatter = logging.Formatter(‘%(asctime)s - %(levelname)s - %(funcName)s - %(module)s - %(lineno)d : %(message)s‘) #输出日志到控制台 pull = logging.StreamHandler() pull.setLevel(level) pull.setFormatter(formatter) #存放日志文件的目录 file_path = FilePath().file_log_path("log.txt") #输出日志到文件 file_log =logging.FileHandler(file_path,encoding="utf-8") file_log.setLevel(level) file_log.setFormatter(formatter) #添加到log里面 log.addHandler(pull) log.addHandler(file_log) #判断日志的级别 if level.upper() == "DEBUG": log.debug(msg)
elif level.upper() == "INFO": log.info(msg)
elif level.upper() == "WARNING": log.warning(msg)
elif level.upper() == "ERROR": log.error(msg)
elif level.upper() == "CRITICAL": log.critical(msg) #最要要移除日志,不然会有重复的 log.removeHandler(pull) log.removeHandler(file_log) def msg_debug(self,msg): self.conf_log("DEBUG",msg)
def msg_info(self,msg): self.conf_log("INFO",msg)
def msg_warning(self,msg): self.conf_log("WARNING",msg)
def msg_error(self,msg): self.conf_log("ERROR",msg)
def msg_critical(self,msg): self.conf_log("CRITICAL",msg)
以上是关于Python日志模块的主要内容,如果未能解决你的问题,请参考以下文章