Python logging模块原理解析及应用
作者:Maruying 时间:2022-04-08 11:14:32
一、logging日志模块等级
常见log级别从高到低:
CRITICAL 》ERROR 》WARNING 》INFO 》DEBUG,默认等级为WARNING,即>=WARNING级别的log才输出。
日志等级(level) | 描述 |
CRITICAL | 当发生严重错误,导致应用程序不能继续运行时记录的信息 |
ERROR | 由于一个更严重的问题导致某些功能不能正常运行时记录的信息 |
WARNING | 当某些不期望的事情发生时记录的信息(如,磁盘可用空间较低),但是此时应用程序还是正常运行的 |
INFO | 信息详细程度仅次于DEBUG,通常只记录关键节点信息,用于确认一切都是按照我们预期的那样进行工作 |
DEBUG | 最详细的日志信息,典型应用场景是 问题诊断 |
二、logging模块的使用方式介绍
logging模块提供了两种记录日志的方式:
第一种方式是使用logging提供的模块级别的函数
第二种方式是使用Logging日志系统的四大组件
其实,logging所提供的模块级别的日志记录函数也是对logging日志系统相关类的封装而已。
(1)logging模块定义的模块级别的常用函数
函数 | 说明 |
---|---|
logging.debug(msg, *args, **kwargs) | 创建一条严重级别为DEBUG的日志记录 |
logging.info(msg, *args, **kwargs) | 创建一条严重级别为INFO的日志记录 |
logging.warning(msg, *args, **kwargs) | 创建一条严重级别为WARNING的日志记录 |
logging.error(msg, *args, **kwargs) | 创建一条严重级别为ERROR的日志记录 |
logging.critical(msg, *args, **kwargs) | 创建一条严重级别为CRITICAL的日志记录 |
logging.log(level, *args, **kwargs) | 创建一条严重级别为level的日志记录 |
logging.basicConfig(**kwargs) | 对root logger进行一次性配置 |
其中logging.basicConfig(**kwargs)函数用于指定“要记录的日志级别”、“日志格式”、“日志输出位置”、“日志文件的打开模式”等信息,其他几个都是用于记录各个级别日志的函数。
(2)logging模块的四大组件
组件 | 说明 |
---|---|
loggers | 提供应用程序代码直接使用的接口 |
handlers | 用于将日志记录发送到指定的目的位置 |
filters | 提供更细粒度的日志过滤功能,用于决定哪些日志记录将会被输出(其它的日志记录将会被忽略) |
formatters | 用于控制日志信息的最终输出格式 |
三、自定义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
来源:https://www.cnblogs.com/Maruying/p/13427596.html
标签:Python,logging,模块
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Go语言Slice作为函数参数的使用
2023-07-16 11:30:20
python自制包并用pip免提交到pypi仅安装到本机【推荐】
2023-12-14 19:33:23
python连接sql server乱码的解决方法
2023-06-27 07:25:17
边框样式的写法总结
2009-01-18 13:00:00
python中的各种运算符介绍
2021-08-09 12:49:04
![](https://img.aspxhome.com/file/2023/8/77618_0s.png)
如何利用JavaScript编写更好的条件语句详解
2023-08-05 04:07:18
土豆网前端概况
2008-01-24 12:06:00
![](https://img.aspxhome.com/file/UploadPic/20081/24/2008124121710861s.jpg)
Django rest framework如何自定义用户表
2022-03-12 01:15:02
![](https://img.aspxhome.com/file/2023/4/75224_0s.png)
使用CSS3和RGBa创建超酷的按钮
2009-06-02 12:41:00
Python list运算操作代码实例解析
2021-11-17 21:44:43
python pyppeteer 破解京东滑块功能的代码
2022-10-24 06:04:10
PHP的mysqli_select_db()函数讲解
2023-06-07 18:59:44
![](https://img.aspxhome.com/file/2023/8/55458_0s.png)
python多线程socket编程之多客户端接入
2021-01-26 10:14:52
![](https://img.aspxhome.com/file/2023/4/69054_0s.png)
如何用Python徒手写线性回归
2023-06-12 13:47:14
![](https://img.aspxhome.com/file/2023/3/59123_0s.png)
交互设计的方法
2010-08-18 12:32:00
![](https://img.aspxhome.com/file/UploadPic/20108/18/01-52s.jpg)
MySQL的添加用户的两种方法
2012-01-29 17:50:10
将MySQL 5.0下的数据导入到MySQL 3.23中
2009-01-04 13:02:00
python 用pandas实现数据透视表功能
2022-04-23 02:49:40
![](https://img.aspxhome.com/file/2023/7/65217_0s.png)
Asp.net清空控件值的方法(可自定义控件类型)
2023-07-22 23:23:16
约瑟夫问题的Python和C++求解方法
2023-12-05 15:09:28