Python 日志基础 - 简单指南
pythonprogrammingserver side programming更新于 2023/11/29 5:25:00
日志用于跟踪软件运行时发生的事件。使用日志,您可以向其代码添加日志调用以指示已发生某些事件。通过这种方式,您可以了解错误、信息、警告等。
日志函数
对于日志,提供了不同的函数。您必须决定何时使用日志。为此,Python 提供了以下内容 -
ogging.info() - 报告程序正常运行期间发生的事件。
logging.warning() - 发出有关特定运行时事件的警告。
logging.error() - 报告错误抑制而不引发异常。
事件的标准严重性级别按严重性递增顺序显示如下。这些级别包括 DEBUG、INFO、WARNING、ERROR、CRITICAL −
DEBUG − 这是详细信息,通常仅在诊断问题时才有用。
INFO − 用于确认一切运行正常。
WARNING − 这是默认级别。它表示发生了意外事件或预示着未来会出现问题,例如内存不足、磁盘空间不足等。
ERROR − 由于更严重的问题,软件无法执行某些功能。
CRITICAL − 严重错误,表示程序本身可能无法继续运行。
日志示例
让我们看一个简单的例子 −
import logging # Prints a message to the console logging.warning('Watch out!')
输出
WARNING:root:Watch out!
Default is Warning
As we explained above, the default level is warning. If you will try to print some other level, it won’t get printed −
import logging # Prints a message to the console logging.warning('Watch out!') # This won't get printed logging.info('Just for demo!')
输出
WARNING:root:Watch out!
记录变量数据
要记录变量数据,您需要使用事件描述消息的格式字符串,并将变量数据作为参数附加。
import logging logging.warning('%s before you %s', 'Look', 'leap!')
输出
WARNING:root:Look before you leap!
在日志消息中添加日期/时间
当我们谈论日志记录时,关键是要包括事件的日期/时间。这主要是警告或错误发生的时间 −
import logging logging.basicConfig(format='%(asctime)s %(message)s') logging.warning('is the Log Time.')
输出
2022-09-19 17:42:47,365 is the Log Time.