python接口自动化(四十)- logger 日志 - 下(超详解)

简介: 日志是非常重要的,用于记录系统、软件操作事件的记录文件或文件集合,可分为事件日志和消息日志。具有处理历史数据、诊断问题的追踪以及理解系统、软件的活动等重要作用,在开发或者测试软系统过程中出现了问题,我们首先想到的就是她——logging。

简介



按照上一篇的计划,这一篇给小伙伴们讲解一下:


(1)多模块使用logging,

(2)通过文件配置logging模块,

(3)自己封装一个日志(logging)类。可能有的小伙伴在这里会有个疑问一个logging为什么分两篇的篇幅来介绍她呢???


那是因为日志是非常重要的,用于记录系统、软件操作事件的记录文件或文件集合,可分为事件日志和消息日志。具有处理历史数据、诊断问题的追踪以及理解系统、软件的活动等重要作用,在开发或者测试软系统过程中出现了问题,我们首先想到的就是她——logging。她可不像泰戈尔说的:“天空没有留下翅膀的痕迹,但我已经飞过”;这个90后的小姑娘,她可是一个爱炫耀,爱显摆的人已经达到了人过留名、雁过留声的境界。好了逗大家一乐,下面开始进入今天的正题。


多模块使用logging



1、父模块fatherModule.py:


1232840-20190524104150326-666690859.png


2、子模块sonModule.py:

1232840-20190524104347368-1905717054.png


3、运行结果,在控制和日志文件log.txt中输出:


1232840-20190524104511872-1375688510.png


首先在父模块定义了logger'fatherModule',并对它进行了配置,就可以在解释器进程里面的其他地方通过getLogger('fatherModule')得到的对象都是一样的,不需要重新配置,可以直接使用。定义的该logger的子logger,


都可以共享父logger的定义和配置,所谓的父子logger是通过命名来识别,任意以'fatherModule'开头的logger都是它的子logger,例如'fatherModule.son'。

  

实际开发一个application,首先可以通过logging配置文件编写好这个application所对应的配置,可以生成一个根logger,如'PythonAPP',然后在主函数中通过fileConfig加载logging配置,接着在application的其他地方、不同的模块中,可以使用根logger的子logger,


如'PythonAPP.Core','PythonAPP.Web'来进行log,而不需要反复的定义和配置各个模块的logger。


4、参考代码


fatherModule.py文件:

 # coding=utf-8
  # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行
  # 2.注释:包括记录创建时间,创建人,项目名称。
  '''
  Created on 2019-5-24
  @author: 北京-宏哥
  Project:学习和使用python的logging日志模块-多模块使用logging
  '''
 # 3.导入模块
 import logging
 import sonModule
 logger = logging.getLogger("fatherModule")
 logger.setLevel(level = logging.INFO)
 handler = logging.FileHandler("log.txt")
 handler.setLevel(logging.INFO)
 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
 handler.setFormatter(formatter)
 console = logging.StreamHandler()
 console.setLevel(logging.INFO)
 console.setFormatter(formatter)
logger.addHandler(handler)
 logger.addHandler(console)
 logger.info("creating an instance of sonModule.sonModuleClass")
 a = sonModule.SonModuleClass()
 logger.info("calling sonModule.sonModuleClass.doSomething")
 a.doSomething()
 logger.info("done with  sonModule.sonModuleClass.doSomething")
 logger.info("calling sonModule.some_function")
 sonModule.som_function()
 logger.info("done with sonModule.some_function")


sonModule.py文件:


 # coding=utf-8
  # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行
  # 2.注释:包括记录创建时间,创建人,项目名称。
  '''
  Created on 2019-5-24
 @author: 北京-宏哥
  Project:学习和使用python的logging日志模块-多模块使用logging
  '''
 # 3.导入模块
 import logging
 module_logger = logging.getLogger("fatherModule.son")
 class SonModuleClass(object):
     def __init__(self):
         self.logger = logging.getLogger("fatherModule.son.module")
         self.logger.info("creating an instance in SonModuleClass")
     def doSomething(self):
         self.logger.info("do something in SonModule")
         a = []
         a.append(1)
         self.logger.debug("list a = " + str(a))
         self.logger.info("finish something in SonModuleClass")
 def som_function():
     module_logger.info("call function some_function")


文件配置logging模块



1、通过logging.config模块配置日志构造信息


logger.conf文件:
[loggers]
keys = root, example01, example02
[logger_root]
level = DEBUG
handlers = hand01, hand02
[logger_example01]
handlers = hand01, hand02
qualname = example01
propagate = 0
[logger_example02]
handlers = hand01, hand03
qualname = example02
propagate = 0
[handlers]
keys = hand01, hand02, hand03
[handler_hand01]
class = StreamHandler
level = INFO
formatter = form01
args=(sys.stdout, )
[handler_hand02]
class = FileHandler
level = DEBUG
formatter = form01
args = ('log/test_case_log.log', 'a')
[handler_hand03]
class = handlers.RotatingFileHandler
level = INFO
formatter = form01
args = ('log/test_case_log.log', 'a', 10*1024*1024,3)
[formatters]
keys = form01, form02
[formatter_form01]
format = %(asctime)s-%(filename)s-[line:%(lineno)d]-%(levelname)s-[LogInfoMessage]: %(message)s
datefmt = %a, %d %b %Y %H:%M:%S
[formatter_form02]
format = %(name)-12s: %(levelname)-8s-[日志信息]: %(message)s
datefmt = %a, %d %b %Y %H:%M:%S


一、实例:


1、实例代码


1232840-20190524125154533-1552402737.png


2、运行结果:


1232840-20190524125217003-505532949.png


3、参考代码:


# coding=utf-8
# 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行
# 2.注释:包括记录创建时间,创建人,项目名称。
'''
Created on 2019-5-27
@author: 北京-宏哥
Project:学习和使用python的logging日志模块-多模块使用logging
'''
# 3.导入模块
import logging
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example01")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')


二、实例


1、实例代码


1232840-20190524125420483-29316957.png


2、运行结果


1232840-20190524125443008-170420070.png


3、参考代码:


# coding=utf-8
# 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行
# 2.注释:包括记录创建时间,创建人,项目名称。
'''
Created on 2019-5-24
@author: 北京-宏哥
Project:学习和使用python的logging日志模块-多模块使用logging
'''
# 3.导入模块
import logging
import logging.config
logging.config.fileConfig("logger.conf")
logger = logging.getLogger("example02")
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')


2、通过JSON文件配置


json配置文件:

{
    "version":1,
    "disable_existing_loggers":false,
    "formatters":{
        "simple":{
            "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        }
    },
    "handlers":{
        "console":{
            "class":"logging.StreamHandler",
            "level":"DEBUG",
            "formatter":"simple",
            "stream":"ext://sys.stdout"
        },
        "info_file_handler":{
            "class":"logging.handlers.RotatingFileHandler",
            "level":"INFO",
            "formatter":"simple",
            "filename":"info.log",
            "maxBytes":"10485760",
            "backupCount":20,
            "encoding":"utf8"
        },
        "error_file_handler":{
            "class":"logging.handlers.RotatingFileHandler",
            "level":"ERROR",
            "formatter":"simple",
            "filename":"errors.log",
            "maxBytes":10485760,
            "backupCount":20,
            "encoding":"utf8"
        }
    },
    "loggers":{
        "my_module":{
            "level":"ERROR",
            "handlers":["info_file_handler"],
            "propagate":"no"
        }
    },
    "root":{
        "level":"INFO",
        "handlers":["console","info_file_handler","error_file_handler"]
    }
}


1、通过JSON加载配置文件,然后通过logging.dictConfig配置logging:

1232840-20190527090325936-961419652.png


2、运行结果:

1232840-20190527091122513-2051246113.png


3、参考代码:

 import json  
  import logging.config  
  import os  
  def setup_logging(default_path = "logging.json",default_level = logging.INFO,env_key = "LOG_CFG"):  
      path = default_path  
      value = os.getenv(env_key,None)  
      if value:  
         path = value  
     if os.path.exists(path):  
         with open(path,"r") as f:  
             config = json.load(f)  
             logging.config.dictConfig(config)  
     else:  
         logging.basicConfig(level = default_level)  
 def func():  
 logging.info("start func")  
     logging.info("exec func")  
     logging.info("end func")  
 if __name__ == "__main__":  
     setup_logging(default_path = "logging.json")  
     func()


3、通过YAML文件配置


1、首先要导入yaml模块,输入命令  python2: pip install yaml          python3:pip install pyyaml


1232840-20190524152951024-76925686.png


2、通过YAML文件进行配置,比JSON看起来更加简介明了:

logging.yaml文件:

version: 1
disable_existing_loggers: False
formatters:
        simple:
            format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
    console:
            class: logging.StreamHandler
            level: DEBUG
            formatter: simple
            stream: ext://sys.stdout
    info_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: INFO
            formatter: simple
            filename: info.log
            maxBytes: 10485760
            backupCount: 20
            encoding: utf8
    error_file_handler:
            class: logging.handlers.RotatingFileHandler
            level: ERROR
            formatter: simple
            filename: errors.log
            maxBytes: 10485760
            backupCount: 20
            encoding: utf8
loggers:
    my_module:
            level: ERROR
            handlers: [info_file_handler]
            propagate: no
root:
    level: INFO
    handlers: [console,info_file_handler,error_file_handler]


3、通过YAML加载配置文件,然后通过logging.dictConfig配置logging:


1232840-20190524153857018-1380309551.png


4、运行结果:


1232840-20190524154010112-374565545.png


5、参考代码:


# coding=utf-8
# 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行
# 2.注释:包括记录创建时间,创建人,项目名称。
'''
Created on 2019-5-24
@author: 北京-宏哥
Project:学习和使用python的logging日志模块-yaml文件配置logging
'''
# 3.导入模块
import yaml
import logging.config
import os
def setup_logging(default_path = "logging.yaml",default_level = logging.INFO,env_key = "LOG_CFG"):
    path = default_path
    value = os.getenv(env_key,None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path,"r") as f:
            config = yaml.load(f)
            logging.config.dictConfig(config)
    else:
        logging.basicConfig(level = default_level)
def func():
    logging.info("start func")
    logging.info("exec func")
    logging.info("end func")
if __name__ == "__main__":
    setup_logging(default_path = "logging.yaml")
    func()


注意:配置文件中“disable_existing_loggers” 参数设置为 False;如果不设置为False,创建了 logger,然后你又在加载日志配置文件之前就导入了模块。logging.fileConfig 与 logging.dictConfig 默认情况下会使得已经存在的 logger 失效。那么,这些配置信息就不会应用到你的 Logger 上。“disable_existing_loggers” = False解决了这个问题


自己封装一个logging类



1、实例代码:


1232840-20190527104809398-14622080.png


2、运行结果:


1232840-20190527115636826-1726374909.png


3、参考代码:


 # coding=utf-8
  # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行
  # 2.注释:包括记录创建时间,创建人,项目名称。
  '''
  Created on 2019-5-27
  @author: 北京-宏哥
  Project:学习和使用python的logging日志模块-自己封装logging
  '''
 # 3.导入模块
 import logging
 class Log(object):
     def __init__(self, name=__name__, path='mylog.log', level='DEBUG'):
         self.__name = name
         self.__path = path
         self.__level = level
         self.__logger = logging.getLogger(self.__name)
         self.__logger.setLevel(self.__level)
     def __ini_handler(self):
         """初始化handler"""
         stream_handler = logging.StreamHandler()
         file_handler = logging.FileHandler(self.__path, encoding='utf-8')
         return stream_handler, file_handler
     def __set_handler(self, stream_handler, file_handler, level='DEBUG'):
         """设置handler级别并添加到logger收集器"""
         stream_handler.setLevel(level)
         file_handler.setLevel(level)
         self.__logger.addHandler(stream_handler)
         self.__logger.addHandler(file_handler)
     def __set_formatter(self, stream_handler, file_handler):
         """设置日志输出格式"""
         formatter = logging.Formatter('%(asctime)s-%(name)s-%(filename)s-[line:%(lineno)d]'
                                       '-%(levelname)s-[日志信息]: %(message)s',
                                       datefmt='%a, %d %b %Y %H:%M:%S')
         stream_handler.setFormatter(formatter)
         file_handler.setFormatter(formatter)
     def __close_handler(self, stream_handler, file_handler):
         """关闭handler"""
         stream_handler.close()
         file_handler.close()
     @property
     def Logger(self):
         """构造收集器,返回looger"""
         stream_handler, file_handler = self.__ini_handler()
         self.__set_handler(stream_handler, file_handler)
         self.__set_formatter(stream_handler, file_handler)
         self.__close_handler(stream_handler, file_handler)
         return self.__logger
 if __name__ == '__main__':
     log = Log(__name__, 'file.log')
     logger = log.Logger
     logger.debug('I am a debug message')
     logger.info('I am a info message')
     logger.warning('I am a warning message')
     logger.error('I am a error message')
     logger.critical('I am a critical message')


小结



1、在yaml文件配置logging的时候,会有个报警信息。有代码洁癖的人,可以处理一下


1232840-20190524154057268-926674480.png


2、是什么原因造成上面的告警呢???是因为:YAML 5.1版本后弃用了yaml.load(file)这个用法,因为觉得很不安全,5.1版本之后就修改了需要指定Loader,通过默认加载器(FullLoader)禁止执行任意函数,该load函数也变得更加安全。


3、解决办法:

  不用改很多代码 加一句就行了 在yaml.load(f, Loader=yaml.FullLoader) 加上 Loader=yaml.FullLoader 就行了。这里要注意的是L要大写的,否则会报错的。


4、加上以后,看一下运行结果:

1232840-20190527090711077-568061041.png


 最后给大家留个彩蛋:文章中有一处bug,会影响运行结果而报错,聪明的你,可以找到吗???嘿嘿!!!欢迎互动和留言

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
13天前
|
数据采集 存储 API
网络爬虫与数据采集:使用Python自动化获取网页数据
【4月更文挑战第12天】本文介绍了Python网络爬虫的基础知识,包括网络爬虫概念(请求网页、解析、存储数据和处理异常)和Python常用的爬虫库requests(发送HTTP请求)与BeautifulSoup(解析HTML)。通过基本流程示例展示了如何导入库、发送请求、解析网页、提取数据、存储数据及处理异常。还提到了Python爬虫的实际应用,如获取新闻数据和商品信息。
|
19天前
|
存储 缓存 JavaScript
python实战篇:利用request库打造自己的翻译接口
python实战篇:利用request库打造自己的翻译接口
31 1
python实战篇:利用request库打造自己的翻译接口
|
29天前
|
Web App开发 Python
在ModelScope中,你可以使用Python的浏览器自动化库
在ModelScope中,你可以使用Python的浏览器自动化库
16 2
|
1月前
|
数据采集 JSON API
如何实现高效率超简洁的实时数据采集?——Python实战电商数据采集API接口
你是否曾为获取重要数据而感到困扰?是否因为数据封锁而无法获取所需信息?是否因为数据格式混乱而头疼?现在,所有这些问题都可以迎刃而解。让我为大家介绍一款强大的数据采集API接口。
|
1月前
|
存储 BI 数据处理
Python自动化 | 解锁高效办公利器,Python助您轻松驾驭Excel!
Python自动化 | 解锁高效办公利器,Python助您轻松驾驭Excel!
|
1月前
|
Python
【python自动化】Playwright基础教程(五)事件操作②悬停&输入&清除精讲
【python自动化】Playwright基础教程(五)事件操作②悬停&输入&清除精讲
47 0
|
2天前
|
人工智能 Python
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
【Python实用技能】建议收藏:自动化实现网页内容转PDF并保存的方法探索(含代码,亲测可用)
20 0
|
12天前
|
Web App开发 测试技术 网络安全
|
16天前
|
JSON 测试技术 持续交付
自动化测试与脚本编写:Python实践指南
【4月更文挑战第9天】本文探讨了Python在自动化测试中的应用,强调其作为热门选择的原因。Python拥有丰富的测试框架(如unittest、pytest、nose)以支持自动化测试,简化测试用例的编写与维护。示例展示了使用unittest进行单元测试的基本步骤。此外,Python还适用于集成测试、系统测试等,提供模拟外部系统行为的工具。在脚本编写实践中,Python的灵活语法和强大库(如os、shutil、sqlite3、json)助力执行复杂测试任务。同时,Python支持并发、分布式执行及与Jenkins、Travis CI等持续集成工具的集成,提升测试效率和质量。
|
1月前
|
Web App开发 前端开发 JavaScript
Python Selenium是一个强大的自动化测试工具
Python Selenium是一个强大的自动化测试工具

热门文章

最新文章