博客
关于我
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 Dict 理解创建和更新字典
查看>>
Python Discord Bot - python clear_reaction() 清除所有反应而不是特定反应
查看>>
python django mysql写入中文乱码_django自动创建的mysql表里面中文乱码问题
查看>>
python docx的超链接网址和链接文本
查看>>
python elasticsearch 导出数据到json文件导入到另一个es中
查看>>
python ETL工具 pyetl
查看>>
Python eval 函数说明
查看>>
python eval简介
查看>>
python excel 饼图 简书_Python实现绘画多个饼图
查看>>
python excel接口自动化测试框架!
查看>>
Python exec 函数解析:探索动态代码执行的无限可能!
查看>>
Python EXEC和__NAME__
查看>>
python file
查看>>
Python FileDialog获取文件夹路径不是文件
查看>>
python filter过滤器的使用_python基础知识分享:zip()、filter函数和reduce如何使用?...
查看>>
python flask 请求code 400, message Bad request version
查看>>
Python Flink Stateful函数入口上的Kafka键访问
查看>>
Python float - str - 浮动怪异
查看>>
Python Flower库:分布式任务管理与监控
查看>>
Python for 循环和迭代器行为
查看>>