博客
关于我
python logging模块学习
阅读量:800 次
发布时间:2023-03-06

本文共 3472 字,大约阅读时间需要 11 分钟。

Python logging实用指南

1. 简单的将日志打印到屏幕

Python内置的logging模块提供了强大的日志功能,默认情况下日志级别为WARNING,日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET。以下示例展示了如何将日志信息打印到屏幕:

import logginglogging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message')

屏幕上打印结果:

WARNING:root:This is warning message

2. 通过logging.basicConfig函数对日志进行格式化和配置

可以通过logging.basicConfig函数对日志的输出格式和方式进行配置,例如指定日志文件名、输出格式、时间格式等:

import logginglogging.basicConfig(    level=logging.DEBUG,    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',    datefmt='%a, %d %b %Y %H:%M:%S',    filename='myapp.log',    filemode='w')logging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message')

myapp.log文件内容示例:

Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug messageSun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info messageSun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

logging.basicConfig函数参数说明:

  • filename:指定日志文件名
  • filemode:指定日志文件的打开模式,支持wa
  • format:指定日志输出格式
  • datefmt:指定日期时间格式
  • level:设置日志级别,默认为WARNING
  • stream:指定日志输出流,默认为sys.stderr

3. 将日志同时输出到文件和屏幕

可以通过定义多个日志处理器,将日志信息同时输出到文件和屏幕:

import logging# 定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误console = logging.StreamHandler()console.setLevel(logging.INFO)formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')console.setFormatter(formatter)logging.getLogger('').addHandler(console)logging.debug('This is debug message')logging.info('This is info message')logging.warning('This is warning message')

屏幕上打印结果:

root: INFO This is info messageroot: WARNING This is warning message

myapp.log文件内容示例:

Sun, 24 May 2009 21:48:54 demo2.py[line:11] DEBUG This is debug messageSun, 24 May 2009 21:48:54 demo2.py[line:12] INFO This is info messageSun, 24 May 2009 21:48:54 demo2.py[line:13] WARNING This is warning message

4. 日志回滚

可以使用RotatingFileHandler对日志进行回滚,设置日志文件最大大小和备份文件数量:

from logging.handlers import RotatingFileHandler# 定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10MBrthandler = RotatingFileHandler('myapp.log', maxBytes=10*1024*1024, backupCount=5)rthandler.setLevel(logging.INFO)formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')rthandler.setFormatter(formatter)logging.getLogger('').addHandler(rthandler)

5. 使用logging.config模块进行日志配置

可以通过配置文件来管理日志设置,例如logger.conf

[loggers]keys = root, example01, example02[logger_root]level = DEBUGhandlers = hand01, hand02[logger_example01]handlers = hand01, hand02qualname = example01propagate = 0[logger_example02]handlers = hand01, hand03qualname = example02propagate = 0[handlers]keys = hand01, hand02, hand03[handler_hand01]class = StreamHandlerlevel = INFOformatter = form02args = (sys.stderr,)[handler_hand02]class = FileHandlerlevel = DEBUGformatter = form01args = ('myapp.log', 'a')[handler_hand03]class = RotatingFileHandlerlevel = INFOformatter = form02args = ('myapp.log', 'a', 10*1024*1024, 5)[formatters]keys = form01, form02[formatter_form01]format = %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)sdatefmt = %a, %d %b %Y %H:%M:%S[formatter_form02]format = %(name)-12s: %(levelname)-8s %(message)sdatefmt =

使用示例:

import loggingimport logging.configlogging.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')

6. logging是线程安全的

logging模块设计为线程安全,适用于多线程环境。

转载地址:http://raafk.baihongyu.com/

你可能感兴趣的文章
Python PIL/Pillow-Pad图像至所需大小(例如,A4)
查看>>
python PIL模框使用
查看>>
Python ping 模块
查看>>
Python Pingouin:搞定各种假设检验和统计模型 !
查看>>
Python pip 国内镜像大全及使用办法
查看>>
Python输入输出练习,运算练习,turtle初步练习
查看>>
Python pip工具使用
查看>>
Python pip配置国内源
查看>>
Python Plotly 将轴数格式化为 %
查看>>
Redis 键值过期操作
查看>>
python predictabel_基于R语言PredictABEL包对Logistic回归模型外部验证
查看>>
Python psycopg2 超时
查看>>
Python Pyinstaller Matplotlibrary
查看>>
Python Pypi 修改 国内源(以豆瓣源为例)
查看>>
Python PyQt5 将不再显示此消息复选框添加到 QMessageBox
查看>>
Python PyQt5:如何使用 PyQt5 显示错误消息
查看>>
Python PYSFTP-以字符串/文本形式传递私钥,而不是传递文件路径
查看>>
Python pytest 面试题!
查看>>
Python pytz 时区函数返回一个相差 9 分钟的时区
查看>>
python rabbitmq实现简单/持久/广播/组播/topic/rpc消息异步发送可配置Django
查看>>