python日志记录库logging介绍

官网Logging HOWTO

Basic Logging Tutorial

Logging日志记录用于追踪软件运行过程中触发的事件。开发人员志将logging calls添加到代码中以指示某件事发生了。事件由消息描述,该消息可以包含一些可变数据(如事件每次出现可能产生不同的数据)。事件有各自的重要性,称为level or severity

When to use logging

Logging为简单的日志记录提供了一些方法可直接调用,debug(), info(), warning(), error(), critical()。可以使用logging的情况见下表

task tool
普通命令或程序输出到控制台 print()
报告程序正常运行过程中触发的事件(状态监测或过失调查 logging.info()logging.debug()详细的诊断)
警告运行时出现的指定事件 warnings.warn():在库代码中,如果问题是可以避免的,并且应修改客户端应用程序以消除警告。logging.warning():如果客户端应用程序无法对这种情况执行任何操作,但仍应注意该事件
报道运行时出现的指定错误 引发异常exception
报告抑制错误而不引发异常(例如,长时间运行的服务器进程中的错误处理程序) logging.error(), logging.exception() or logging.critical()适用于特定错误和应用程序领域

logging函数按照它们被使用来追踪的事件level or severity命名,标准水平及其适用性如下(按严重程度的增加顺序)

Level When it’s used
DEBUG 详细信息,通常仅在诊断问题时才有意义
INFO 确认事情正在按预期进行
WARNING 迹象表明发生了意想不到的事情,或表明在不久的将来出现了一些问题(如磁盘空间低),程序仍在正常工作
ERROR 由于更严重的问题,该软件无法执行某些功能
CRITICAL 一个严重的错误,表明程序本身可能无法继续运行

默认是WARNING,表明只有这个级别及以上的事件才会被跟踪,除非修改日志包配置
跟踪的事件可以以不同的方式处理。处理跟踪事件的最简单方法是将它们打印到控制台。另一种常见的方法是将它们写入磁盘文件

A simple example

>>>import logging
>>>logging.warning('watch out')  # 输出信息到控制台
WARNING:root:watch out
>>>logging.info('told you')  # 不会打印出任何信息

INFO信息没有输出是因为它的级别低于WARNING,输出信息包括指示级别WARNING和描述watch out。输出格式也可以修改。

Logging to a file

一个常见的情况是在文件中记录logging事件

import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logging.debug('this message should go to the log file')
logging.info('so should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')

运行上面代码生成文件example.log,内容如下

DEBUG:root:this message should go to the log file
INFO:root:so should this
WARNING:root:And this, too
ERROR:root:And non-ASCII stuff, too, like Øresund and Malmö

设置的levelDEBUG,因此所有信息都输出
每次运行都会添加信息到文件中,如果想只记录最新的信息,使用filemode参数

logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

Logging from multiple modules

如果你的程序包含多个模块,可以相互调用myapp.py调用mylib.py,信息全都输出在myapp.log

# mylib.py
import logging
def do_something():
    logging.info('do something')
# myapp.py
import mylib
import logging
def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logging.info('start')
    mylib.do_something()
    logging.info('finish')
if __name__ == '__main__':
    main()
INFO:root:start
INFO:root:do something
INFO:root:finish

Logging variable data

要记录变量数据,使用事件描述消息的格式字符串,并将变量数据附加为参数。

扫描二维码关注公众号,回复: 15189015 查看本文章
import logging
logging.warning('%s before you %s', 'look', 'leap!')
WARNING:root:look before you leap!

此处的格式使用的旧%风格,最新的格式也支持,参考 Using particular formatting styles throughout your application

Changing the format of displayed messages

要更改用于显示消息的格式,需要指定要使用的格式

import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too

此处的root消失

Displaying the date/time in messages

要显示事件的日期和时间,在格式字符串中放置%(asctime)

import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')
2022-09-20 14:49:48,927 is when this event was logged.

修改日期格式,传入参数datefmt

import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
09/20/2022 02:50:34 PM is when this event was logged.

以上是基础的logging教程,对于简单的使用和运行是足够的,如果需要更高级的教程参考Logging Cookbook

猜你喜欢

转载自blog.csdn.net/weixin_45526117/article/details/126943685