python 包之 logging 日志处理教程

网友投稿 863 2022-05-29

一、基本方法

默认情况下日志打印只显示大于等于 WARNING 级别的日志

FATAL:致命错误

python 包之 logging 日志处理教程

CRITICAL:特别糟糕的事情,如内存耗尽、磁盘空间为空,一般很少使用

ERROR:发生错误时,如IO操作失败或者连接问题

WARNING:发生很重要的事件,但是并不是错误时,如用户登录密码错误

INFO:处理请求或者状态变化等日常事务

DEBUG:调试过程中使用DEBUG等级,如算法中每个循环的中间状态

import logging logging.debug('It is a debug') logging.info('It is a info') logging.warning('It is a warning') logging.error('It is a Error') logging.critical('It is a critical')

二、设置日志级别

import logging logging.basicConfig(level=logging.DEBUG) logging.debug('Python debug')

三、将信息记录到文件

import logging logging.basicConfig(filename='logging.text', level=logging.DEBUG) logging.debug('It is a debug') logging.info('It is a info') logging.warning('It is a warning')

四、更改消息格式

%(levelno)s:打印日志级别的数值

%(levelname)s:打印日志级别的名称

%(pathname)s:打印当前执行程序的路径,其实就是sys.argv[0]

%(filename)s:打印当前执行程序名

%(funcName)s:打印日志的当前函数

%(lineno)d:打印日志的当前行号

%(asctime)s:打印日志的时间

%(thread)d:打印线程ID

%(threadName)s:打印线程名称

%(process)d:打印进程ID

%(message)s:打印日志信息

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.')

五、配置日志

创建日志记录配置文件并使用该 fileConfig() 功能读取它

logging.conf 配置文件:

[loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt=

使用

import logging import logging.config logging.config.fileConfig('logging.conf') logger = logging.getLogger('simpleExample') logging.debug('It is a debug') logging.info('It is a info') logging.warning('It is a warning') logging.error('It is a Error') logging.critical('It is a critical')

Python

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:一文了解 JAVA 类加载机制
下一篇:如何取消LaTeX插入图片时边框出现虚线阴影?
相关文章