Python基础之logging模块知识总结
作者:_雪辉_ 时间:2021-12-20 04:20:07
前言
logging模块是Python内置的标准模块,主要用于输出脚本运行日志,可以设置输出日志的等级、日志保存路径等。
可以通过设置不同的日志等级,在 release 版本中只输出重要信息,而不显示大量的调试信息
logging 可以决定将信息输出位置和内容
logging 线程更安全
一、日志级别
级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG
debug : 打印全部日志,详细信息,通常只出现在诊断问题
info : 打印info,warning,error,critical级别的日志,正常输出
warning : 打印warning,error,critical级别的日志,部分异常,不影响程序
error : 打印error,critical级别的日志,影响程序部分功能
critical : 打印critical级别,影响程序运行
import logging # 引入logging模块
# 将信息打印到控制台上
logging.debug("debug")
logging.info("info")
logging.warning("warning")
logging.error("error")
logging.critical("critical")
[root@zijie ~]# python log.py
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
默认生成的root logger的level是logging.WARNING,低于该级别不输出,如果要展示低于WARNING级别的内容,可以引入logging.basicConfig指定日志级别logging.basicConfig(level=logging.DEBUG)
二、basicConfig
格式 | 描述 |
filename | 指定使用指定的文件名而不是 StreamHandler 创建 FileHandler。 |
filemode | 如果指定 filename,则以此模式打开文件(‘r'、‘w'、‘a')。默认为“a”。 |
format | 为处理程序使用指定的格式字符串。 |
datefmt | 使用 time.strftime() 所接受的指定日期/时间格式。 |
style | 如果指定了格式,则对格式字符串使用此样式。'%' 用于 printf 样式、'{' 用于 str.format()、'$' 用于 string。默认为“%”。 |
level | 将根记录器级别设置为指定的级别。默认生成的 root logger 的 level 是 logging.WARNING,低于该级别的就不输出了。级别排序:CRITICAL > ERROR > WARNING > INFO > DEBUG。(如果需要显示所有级别的内容,可将 level=logging.NOTSET) |
stream | 使用指定的流初始化 StreamHandler。注意,此参数与 filename 不兼容——如果两者都存在,则会抛出 ValueError。 |
handlers | 如果指定,这应该是已经创建的处理程序的迭代,以便添加到根日志程序中。任何没有格式化程序集的处理程序都将被分配给在此函数中创建的默认格式化程序。注意,此参数与 filename 或 stream 不兼容——如果两者都存在,则会抛出 ValueError。 |
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s %(levelname)s %(message)s',
datefmt='%a %d %b %Y %H:%M:%S',
filename='xuehui.log',
filemode='w')
logging.info('This is a info.')
logging.debug('This is a debug message.')
logging.warning('This is a warning.')
三、日志写文件
import logging
import os.path
import time
#创建logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# 创建handler,用于写入日志文件
logdate = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
log_path = 'logs/'
log_name = log_path + logdate + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG)
# 定义输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
# 将logger添加到handler
logger.addHandler(fh)
# 日志
logger.debug('this is a logger debug message')
logger.info('this is a logger info message')
logger.warning('this is a logger warning message')
logger.error('this is a logger error message')
logger.critical('this is a logger critical message')
四、traceback记录
import logging
import os.path
import time
#创建logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# 创建handler,用于写入日志文件
logdate = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
log_path = 'logs/'
log_name = log_path + logdate + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG)
# 定义输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
# 将logger添加到handler
logger.addHandler(fh)
# 日志
try:
open('/data/exist', 'rb')
except BaseException as e:
logger.error('Failed to open file', exc_info=True)
来源:https://blog.csdn.net/qq_42979842/article/details/116875907
标签:Python,logging,模块
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
网红编程语言Python将纳入高考你怎么看?
2022-06-28 15:48:12
![](https://img.aspxhome.com/file/2023/3/92233_0s.png)
python重要函数eval多种用法解析
2023-02-08 20:16:46
python抽象基类用法实例分析
2021-03-04 11:06:25
Python中如何创建多线程?
2022-11-25 15:52:34
js三维正方体(兼容ie/ff)
2008-04-12 14:38:00
![](https://img.aspxhome.com/file/UploadPic/20084/12/2008412144141850s.gif)
动态导航设计
2008-09-21 13:40:00
![](https://img.aspxhome.com/file/UploadPic/20089/21/2008921134132724s.jpg)
python Multiprocessing.Pool进程池模块详解
2023-08-25 09:24:59
Django实现发送邮件功能
2021-05-13 10:25:44
![](https://img.aspxhome.com/file/2023/0/82520_0s.jpg)
如何在SQL2000的查询中使用XML-Data?
2010-06-18 19:26:00
Python数据可视化之Seaborn的使用详解
2022-10-25 21:57:31
![](https://img.aspxhome.com/file/2023/2/89292_0s.png)
Python对列表的操作知识点详解
2022-05-08 09:06:39
![](https://img.aspxhome.com/file/2023/9/82939_0s.png)
python搭建微信公众平台
2022-05-24 00:14:09
python中os和sys模块的区别与常用方法总结
2022-05-26 18:04:24
golang开发go包依赖管理godep使用教程
2023-10-16 04:09:31
解决python多行注释引发缩进错误的问题
2022-02-08 04:19:53
在Mac上删除自己安装的Python方法
2021-03-22 22:10:57
深度学习入门之Pytorch 数据增强的实现
2021-04-05 22:26:07
![](https://img.aspxhome.com/file/2023/0/87810_0s.jpg)
一百多行python代码实现抢票助手
2022-05-20 00:55:52
利用python库在局域网内传输文件的方法
2021-01-29 03:41:48
使用setup.py安装python包和卸载python包的方法
2023-01-31 02:20:47