Files
rikako-note/python/py log.md
2024-12-04 20:42:36 +08:00

1.9 KiB
Raw Blame History

python log

Logging use

可以通过logger = getLogger(__name__)创建一个logger之后可以通过logger来访问日志功能。

针对logger对象可以调用debug(), info(), warning(), error(), critical()方法。

python中日志级别及其适用性如下

级别 实用性
DEBUG 详细信息,通常只在调试时用到
INFO 用于确认应用正在按照预期执行
WARNING 代表存在非预期事件发生,但是应用仍然按期望运行
ERROR 代表应用存在问题,部分功能可能无法正常访问
CRITIAL 严重错误,代表应用不能继续执行

logger默认的隔离级别是WARNING, 只有WARNING隔离级别或更高的隔离级别,日志才会被输出。该默认隔离级别也可以手动修改。

日志使用简单示例

import logging
logging.warning('Watch out!')  # will print a message to the console
logging.info('I told you so')  # will not print anything

上述示例,其会输出

WARNING:root:Watch out!

默认输出的日志隔离级别为WARNINGinfo信息并不会被输出

当直接调用logging中的方法时其并没有创建logger对象方法调用是针对root logger对象的。

loggging to file

将日志输出到文件的示例如下所示:

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

其输出内容如下所示:

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