博客
关于我
python logging模块学习
阅读量:803 次
发布时间: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 | pyautogui,一个超酷的 Python 库!
查看>>
python | pybaobabdt,一个超强的 决策树可视化 Python 库!
查看>>
python | pycco,一个神奇的 Python 库!
查看>>
python | pyg2plot,一个有趣的 数据可视化 Python 库!
查看>>
python | pymc,一个超强的 Python 库!
查看>>
python | pynsist,一个强大的 Python 库!
查看>>
python | pyparsing,一个强大的 Python 库!
查看>>
python | pyqtgraph,一个神奇的 Python 库!
查看>>
python读取文本文件数据
查看>>
python | Python mock对象与测试替身
查看>>
python | Python pandas实现数据追加和合并的最佳方法
查看>>
python | Python 中检查一个数字是否是三态数
查看>>
python | Python 蒙特卡洛模拟
查看>>
python | python-docx,一个超厉害的 Python 库!
查看>>
python | Python中使用@property装饰器
查看>>
python | Python中的functools模块高级应用
查看>>
python | Python中的itertools模块使用技巧
查看>>
python | Python中的事件驱动编程模型
查看>>
python | Python中的内存池与缓存机制
查看>>
python | Python中的弱引用与内存管理
查看>>