千家信息网

Python中logging模块的知识有哪些

发表于:2025-02-02 作者:千家信息网编辑
千家信息网最后更新 2025年02月02日,这篇文章主要介绍"Python中logging模块的知识有哪些",在日常操作中,相信很多人在Python中logging模块的知识有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希
千家信息网最后更新 2025年02月02日Python中logging模块的知识有哪些

这篇文章主要介绍"Python中logging模块的知识有哪些",在日常操作中,相信很多人在Python中logging模块的知识有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"Python中logging模块的知识有哪些"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

前言

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.pyWARNING:root:warningERROR:root:errorCRITICAL: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 logginglogging.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 loggingimport os.pathimport time#创建loggerlogger = 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_namefh = 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添加到handlerlogger.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 loggingimport os.pathimport time#创建loggerlogger = 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_namefh = 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添加到handlerlogger.addHandler(fh)# 日志try:    open('/data/exist', 'rb')except BaseException as e:    logger.error('Failed to open file', exc_info=True)

    到此,关于"Python中logging模块的知识有哪些"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

    0