PHP头条
热点:

Python logging模块原理及应用代码解析


本篇文章小编给大家分享一下Python logging模块原理及应用代码解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、logging日志模块等级

常见log级别从高到低:

CRITICAL 》ERROR 》WARNING 》INFO 》DEBUG,默认等级为WARNING,即>=WARNING级别的log才输出。

Python logging模块原理及应用代码解析

二、logging模块的使用方式介绍

logging模块提供了两种记录日志的方式:

第一种方式是使用logging提供的模块级别的函数

第二种方式是使用Logging日志系统的四大组件

其实,logging所提供的模块级别的日志记录函数也是对logging日志系统相关类的封装而已。

(1)logging模块定义的模块级别的常用函数

Python logging模块原理及应用代码解析

其中logging.basicConfig(**kwargs)函数用于指定“要记录的日志级别”、“日志格式”、“日志输出位置”、“日志文件的打开模式”等信息,其他几个都是用于记录各个级别日志的函数。

(2)logging模块的四大组件

Python logging模块原理及应用代码解析

三、自定义Logger模块类

# testLog1.py

import logging
import time

class Logger():

  def __init__(self, logger, level=logging.DEBUG):
    '''     : 自定义Logger模块类
    : logger: logger名
    : level: 日志级别
    '''

    # 创建一个logger
    self.logger = logging.getLogger(logger)
    self.logger.setLevel(level)

    # 定义handler的输出格式
    curr_time = time.strftime("%Y-%m-%d")
    self.LogFileName = 'log' + curr_time + '.txt'
    fmt = logging.Formatter('%(asctime)s - %(filename)s:[%(lineno)s] - [%(levelname)s] - %(message)s')

    # asctime: 日志事件发生的时间
    # filename: 源文件的名称部分,包含文件后缀
    # lineno: 调用日志记录函数的源代码所在的行号
    # evelname: 该日志记录的文字形式的日志级别
    # message: 日志记录的文本内容

    # 创建一个handler, 用于写入日志文件
    fh = logging.FileHandler(self.LogFileName)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(fmt)

    # 再创建一个handler,用于输出到控制台
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(fmt)

    # 给logger添加handler
    self.logger.addHandler(fh)
    self.logger.addHandler(ch)

    # level优先级
    # logger.setLevel > handler.setLevel > logging.basicConfig

if __name__ == "__main__":
  log = Logger(__name__, level=logging.DEBUG)
  log.logger.debug('debug')
  log.logger.log(logging.DEBUG, 'debug')# 执行testLog1.py,则控制台输出如下:2020-08-03 20:36:47,104 - testLog1.py:[117] - [DEBUG] - debug2020-08-03 20:36:47,104 - testLog1.py:[118] - [DEBUG] - debug# 日志文件记录如下:2020-08-03 20:36:15,982 - testLog1.py:[117] - [DEBUG] - debug2020-08-03 20:36:15,982 - testLog1.py:[118] - [DEBUG] - debug
# testLog2.py

from testLog1 import Logger
import traceback

log = Logger(__name__)
def func():
  try:
    assert 1==2
  except Exception:
    log.logger.info('测试失败,输出信息如下:{}'.format(traceback.format_exc()))    # traceback.format_exc() 会返回异常信息的字符串

if __name__ == "__main__":
  func()# 执行testLog2.py,则控制台输出如下:2020-08-03 20:43:44,907 - testLog2.py:[11] - [INFO] - 测试失败,输出信息如下:Traceback (most recent call last):  File "E:/imooc/testLog.py", line 9, in func    assert 1==2AssertionError# 日志文件记录如下:2020-08-03 20:43:44,907 - testLog2.py:[11] - [INFO] - 测试失败,输出信息如下:Traceback (most recent call last):  File "E:/imooc/testLog.py", line 9, in func    assert 1==2AssertionError
  • 上一篇: 基于parameters参数实现参数化过程代码解析

  • 下一篇: Spring Cloud Gateway重试机制原理代码解析

www.phpzy.comtrue/php/39460.htmlTechArticlePython logging模块原理及应用代码解析 本篇文章小编给大家分享一下Python logging模块原理及应用代码解析,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需...

相关文章

    暂无相关文章

PHP之友评论

今天推荐