python之logging模块基本用法

logging是python标准库中的模块,用于给程序添加日志,借此方便我们回溯程序的执行过程。

以下面代码为例,介绍logging模块的基本用法:

import logging

logging.basicConfig(filename="example.log", filemode="a", format="%(levelname)s:%(message)s", level=logging.DEBUG)

logging.debug(">>>>>Log Message: %s, %s" % ("Hello", "I‘m debug log"))
logging.info(">>>>>Log Message: %s, %s" % ("Hello", "I‘m info log"))
logging.warning(">>>>>Log Message: %s, %s" % ("Hello", "I‘m warning log"))
logging.error(">>>>>Log Message: %s, %s" % ("Hello", "I‘m error log"))
logging.critical(">>>>>Log Message: %s, %s" % ("Hello", "I‘m critical log"))

该段代码会把日志输出到名为"example.log"的文件中,并规定了日志的输出格式及最低日志级别,输出结果如下:

DEBUG:>>>>>Log Message: Hello, I‘m debug log
INFO:>>>>>Log Message: Hello, I‘m info log
WARNING:>>>>>Log Message: Hello, I‘m warning log
ERROR:>>>>>Log Message: Hello, I‘m error log
CRITICAL:>>>>>Log Message: Hello, I‘m critical log 

日志级别

logging模块中初始定义了五个日志级别,如表格所示。由上到下,级别对应的严重程度依次增加。在文章开头的例子中,我们调用logging.basicConfig()配置了想要输出的日志最低级别为DEBUG,这意味着DEBUG及其以上等级的日志都会被输出。同理,如果我们只想输出ERROR及以上的日志,则令level=logging.ERROR即可。


级别


何时使用


DEBUG


细节信息,仅当诊断问题时适用。


INFO


确认程序按预期运行


WARNING


表明有已经或即将发生的意外(例如:磁盘空间不足)。程序仍按预期进行


ERROR


由于严重的问题,程序的某些功能已经不能正常执行


CRITICAL


严重的错误,表明程序已不能继续执行

LogRecord属性

在logging.basicConfig()中,我们使用了format="%(levelname)s:%(message)s"来规定日志的输出格式。其中levelname和message都是LogRecord属性,它们能出现在format字符串中,令输出结果带上了日志等级名、日志消息。其他可以出现在format字符串中的内容,参见下表:


属性名称


格式


描述


args


不需要格式化。


The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).


asctime


%(asctime)s


Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896‘ (the numbers after the comma are millisecond portion of the time).


created


%(created)f


Time when the LogRecord was created (as returned by time.time()).


exc_info


不需要格式化。


Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.


filename


%(filename)s


Filename portion of pathname.


funcName


%(funcName)s


Name of function containing the logging call.


levelname


%(levelname)s


Text logging level for the message (‘DEBUG‘‘INFO‘‘WARNING‘‘ERROR‘‘CRITICAL‘).


levelno


%(levelno)s


Numeric logging level for the message (DEBUGINFOWARNINGERRORCRITICAL).


lineno


%(lineno)d


Source line number where the logging call was issued (if available).


message


%(message)s


The logged message, computed as msg % args. This is set when Formatter.format() is invoked.


module


%(module)s


模块 (filename 的名称部分)。


msecs


%(msecs)d


Millisecond portion of the time when the LogRecord was created.


msg


不需要格式化。


The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see 使用任意对象作为消息).


name


%(name)s


Name of the logger used to log the call.


pathname


%(pathname)s


Full pathname of the source file where the logging call was issued (if available).


process


%(process)d


进程ID(如果可用)


processName


%(processName)s


进程名(如果可用)


relativeCreated


%(relativeCreated)d


Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.


stack_info


不需要格式化。


Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.


thread


%(thread)d


线程ID(如果可用)


threadName


%(threadName)s


线程名(如果可用)

输出方式

在logging.basicConfig()中,我们使用了filename="example.log", filemode="a"来令日志输出至某个文件。如果不带filename和filemode参数,则会把日志直接打印出来。filemode参数值默认为"a",意味着在原有日志的基础上,追加写新的日志;如果不想追加写新的日志,而是覆盖原有的日志,令filemode="w"即可。

最后说明,本篇文章只对logging模块的基本用法做了介绍,logging模块还有更多强大的功能供使用,待后续进一步介绍。

参考资料

https://docs.python.org/zh-cn/3/library/logging.html

原文地址:https://www.cnblogs.com/zhuosanxun/p/11367934.html

时间: 2024-07-31 14:20:52

python之logging模块基本用法的相关文章

Python中logging模块的基本用法

在 PyCon 2018 上,Mario Corchero 介绍了在开发过程中如何更方便轻松地记录日志的流程. 整个演讲的内容包括: 为什么日志记录非常重要 日志记录的流程是怎样的 怎样来进行日志记录 怎样进行日志记录相关配置 日志记录使用常见误区 下面我们来梳理一下整个演讲的过程,其实其核心就是介绍了 logging 模块的使用方法和一些配置. 日志记录的重要性 在开发过程中,如果程序运行出现了问题,我们是可以使用我们自己的 Debug 工具来检测到到底是哪一步出现了问题,如果出现了问题的话,

python的logging模块

1.简单的将日志打印到屏幕 import logging logging.debug('This is debug message') logging.info('This is info message') logging.warning('This is warning message') 屏幕上打印: WARNING:root:Thisis warning message 默认情况下,logging将日志打印到屏幕,日志级别为WARNING: 日志级别大小关系为:CRITICAL > ER

python之logging模块的使用

python的logging模块是用来写日志的,是python的标准模块. logging的结构 查看logging的python源码,可知主要有四个类实现功能: Loggers:提供应用程序直接使用的接口,如相关的配置设置: Handlers:将Loggers产生的日志传到指定位置,设置日志保存的位置: Filters:对输出日志进行过滤操作: Formatters:控制日志的输出格式: 日志记录的级别 DEBUG:优先级10,记录调试的详细信息,只在调试时开启: INFO:优先级20,记录普

Python基础-----logging模块

#!/usr/bin/env python#-*- coding:utf-8 -*- ########################################################################################################################################################灵活配置日志级别,日志格式,输出位置#####################################

python使用logging模块方法 教程

logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同的日志等级,在release版本中只输出重要信息,而不必显示大量的调试信息:print将所有信息都输出到标准输出中,严重影响开发者从标准输出中查看其它数据:logging则可以由开发者决定将信息输出到什么地方,以及怎么输出: logging模块的日志级别 logging模块默认定义了以下几个日志等级,它允许开发人员自定义其他日

python中logging模块的一些简单用法

用Python写代码的时候,在想看的地方写个print xx 就能在控制台上显示打印信息,这样子就能知道它是什么了,但是当我需要看大量的地方或者在一个文件中查看的时候,这时候print就不大方便了,所以Python引入了logging模块来记录我想要的信息.print也可以输入日志,logging相对print来说更好控制输出在哪个地方,怎么输出及控制消息级别来过滤掉那些不需要的信息. 1.日志级别 import logging # 引入logging模块 # 将信息打印到控制台上 loggin

python中logging模块的使用

一.基本用法 只需要基本的配置,就可以使用了. import logging def fun2(): logging.basicConfig(filename="fun2.log",format="%(asctime)s %(message)s",level=logging.DEBUG) logging.debug("this is fun2 log") 二.进行详细配置 首先添加一个fileHandler来配置记录的文件,Formatter来设

python的logging模块详解

日志级别 >>>import logging >>>logging.NOTSET 0 >>>logging.DEBUG 10 >>>logging.INFO 20 >>>logging.WARN 30 >>>logging.ERROR 40 >>>logging.CRITICAL 50 >>>logging._levelNames {0:'NOTSET', 10:

Python的logging模块、os模块、commands模块与sys模块

一.logging模块 import logging logging.debug('This is debug message') logging.info('This is info message') logging.warning('This is warning message') 屏幕上打印: WARNING:root:This is warning message 默认情况下,logging将日志打印到屏幕,日志级别为WARNING: 日志级别大小关系为:CRITICAL > ERR