`
crazier9527
  • 浏览: 993874 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Python的标准logging模块(1)

阅读更多

Python的标准logging模块

Python 2.3 introduced the logging module to the Python standard library. logging provides a standard interface for outputting information from a running application. The classic example of a logging mechanism is writing data to a text file, which is a plain old log file. While the log file is likely the most common form of logging, the logging module provides the ability to send information to file-like objects, TCP and UDP sockets, email servers, the Unix syslog, the NT event log, memory buffers, and HTTP servers in addition to "real" files.

Python2.3,Python的标准库加入了logging模块.logging模块给运行中的应用提供了一个标准的信息输出接口.典型的logging机制实现是把要输出的数据简单地写到一个txt文件中去.log文件的方式是一种常见的打log的方式,logging模块提供的更多,它可以把输出信息输出到所有类文件的对象中去,甚至TCPUDPsockets,email服务器,Unixsyslog系统,NT系列的事件log系统,内存的bufferHTTP服务器,当然还有真正的文件中去.

The logging library takes a modular approach and offers the several categories of components: loggers, handlers, filters, and formatters. Loggers expose the interface that application code directly uses. Handlers send the log records to the appropriate destination. Filters provide a finer grained facility for determining which log records to send on to a handler. Formatters specify the layout of the resultant log record.

Logging库被设计成模块的方式,它提供了以下几个子模块:loggers,handlers,filtersformatters.Loggers把应用需要直接调用的接口暴露出来.Handlerslog记录发到相应的目的地.Filters决定哪些记录需要发给handler.Formatters定义了log记录的输出格式.

Loggers

Logger objects have a threefold job. First, they expose several methods to application code so that applications can log messages at runtime. Second, logger objects determine which log messages to act upon based upon severity (the default filtering facility) or filter objects. Third, logger objects pass along relevant log messages to all interested log handlers.

Logger对象扮演了三重角色.首先,它暴露给应用几个方法以便应用可以在运行时写log.其次,Logger对象按照log信息的严重程度或者根据filter对象来决定如何处理log信息(默认的过滤功能).最后,logger还负责把log信息传送给相关的loghandlers.

The most widely used methods on logger objects fall into two categories: configuration and message sending.

Logger中最长使用的方法分成两部分中:configurationmessage sending.

The configuration methods are:

用于Configuration的方法:

  • setLevel(level)
  • addFilter(filter)
  • removeFilter(filter)
  • addHandler(handler)
  • removeHandler(handler)

setLevel() specifies the lowest-severity log message a logger will handle, where debug is the lowest built-in severity level and critical is the highest built-in severity. For example, if the severity level is info, the logger will handle only info, warning, error, and critical messages and will ignore debug messages.

addFilter() and removeFilter() add and remove filter objects from the logger object. This article does not address filters.

setLevel()方法定义了一个logger处理的最底严重程度(比如说中//底三种,我定义为中,那么只有严重程度为中或者高的log才会被处理).debug级别是内置的最低级别,critical是最高级别.举例来说,如果严重级别设为info,logger仅仅处理info,warning,errorcritical级的log,debug级别的则忽略掉.

With the logger object configured, the following methods create log messages:

根据logger对象的设置,以下的方法被用来写log:

  • debug(log_message, [*args[, **kwargs]])
  • info(log_message, [*args[, **kwargs]])
  • warning(log_message, [*args[, **kwargs]])
  • error(log_message, [*args[, **kwargs]])
  • critical(log_message, [*args[, **kwargs]])
  • exception(message[, *args])
  • log(log_level, log_message, [*args[, **kwargs]])

debug(), info(), warning(), error(), and critical() all create log records with a message of log_message and a level that corresponds to their respective method names. log_message is actually a format string, which may contain the standard string substitution syntax of %s, %d, %f, and so on. *args is a list of objects that correspond with the substitution fields in log_message. With regard to **kwargs, the logging methods care only about a keyword of exc_info and use it to determine whether to log exception information.

debug(),info(),warning(),error()critical()方法用一个log_message格式字符串和与之对应的各个参数来生成log信息.log_message实际上是一个格式字符串,它可以包含诸如%s,%d,%f此类的替换符号.*args是实际要替换%s,%d,%f参数的列表.至于这个**kwargs关键字参数,logging只处理一个关键字exc_info,这个关键字决定是否对异常信息打log.

exception() creates a log message similar to error(). The difference is that exception() dumps a stack trace along with it. Call this method only from an exception handler.

exception()error()方法基本一样.不同之处是exception()多出一个stack trace用于转储.exception()方法只能从一个exception handler里面调用.

log() takes a log level as an explicit argument. This is a little more verbose for logging messages than using the log level convenience methods listed above, but this is how to log at custom log levels.

Log()方法显式的带一个level参数,用这个可以得到比使用上面所列举的方法更为详细的log信息,这属于自定义log信息的范畴了.

logging.getLogger([name]) returns a reference to a logger instance with a name of name if a name is provided, or root if not. The names are period-separated (.) hierarchical structures. Multiple calls to logging.getLogger() with the same name will return a reference to the same logger object. Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of foo, loggers with names of foo.bar, foo.bar.baz, and foo.bam are all children of foo. Child loggers propagate messages up to their parent loggers. Because of this, it is unnecessary to define and configure all the loggers an application uses. It is sufficient to configure a top-level logger and create child loggers as needed.

Logging.getLogger([name])方法返回一个logger实例的引用,如果name参数给出,则用这个参数的值作为名字,如果没有则用root做默认值.名字是以点号分割的命名方式命名的(a.b.c).对同一个名字的多个调用logging.getLogger()方法会返回同一个logger对象.这种命名方式里面,后面的loggers是前面logger的子.比如说,有一个名字是foologger,那么诸如foo.bar,foo.bar.bazfoo.bam这样的logger都是foo这个logger的子,loggers自动继承父loggerslog信息,正因为此,没有必要把一个应用的所有logger都配置一边,只要把顶层的logger配置好了,然后子logger根据需要继承就行了.

Handlers

Handler objects are responsible for dispatching the appropriate log messages (based on the log messages' severity) to the handler's specified destination. Logger objects can add zero or more handler objects to themselves with an addHandler() method. As an example scenario, an application may want to send all log messages to a log file, all log messages of error or higher to stdout, and all messages of critical to an email address. This scenario requires three individual handlers where each hander is responsible for sending messages of a specific severity to a specific location.

Handler对象负责分配合适的log信息(基于log信息的严重程度)handler指定的目的地.Logger对象可以用addHandler()方法添加零个或多个handler对象到它自身.一个常见的场景是,一个应用可能希望把所有的log信息都发送到一个log文件中去,所有的error级别以上的log信息都发送到stdout,所有criticallog信息通过email发送.这个场景里要求三个不同handler处理,每个handler负责把特定的log信息发送到特定的地方.

The standard library includes the following handlers:

标准库里面包括以下的handlers:

  • StreamHandler
  • FileHandler
  • RotatingFileHandler
  • TimedRotatingFileHandler
  • SocketHandler
  • DatagramHandler
  • SysLogHandler
  • NTEventLogHandler
  • SMTPHandler
  • MemoryHandler
  • HTTPHandler

This article uses only StreamHandler and FileHandler in its examples.

本文里面只用到了StreamHandlerFileHandler

There are very few methods in a handler for application developers to concern themselves with. The only handler methods that seem relevant for application developers who are using the built-in handler objects (that is, not creating custom handlers) are the following configuration methods:

Handler里面提供给应用开发者的只有很少的几个方法可用.对使用内置的handler(就是说不是自定义的handlers)的开发者可用的配置方法如下:

  • setLevel(level)
  • setFormatter(formatter)
  • addFilter(filter)
  • removeFilter(filter)

The setLevel() method, just as in logger objects, specifies the lowest severity that will be dispatched to the appropriate destination. Why are there two setLevel() methods? The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on. setFormatter() selects a Formatter object for this handler to use. addFilter() and removeFilter() respectively configure and deconfigure filter objects on handlers.

setLevel()方法跟logger对象里面的setLevel()一样,也是用于设定一个最低分发log信息的级别.为什么有两个setLevel()?logger的严重等级用于决定那个级别的log信息可以分发到它的handlers.handler里面的level设置用于控制那些个log信息是handler需要转寄的.setFormatter()方法选定一个格式化对象给它自己用.addFilter()removeFilter()分别用于为handler增加一个filter和删除一个filter.

Application code should not directly instantiate and use handlers. Instead, the logging.Handler class is a base class that defines the interface that all Handlers should have and establishes some default behavior that child classes can use (or override).

应用里面Handler不应该被直接实例化.相反,应该用logging.Handler类作所有Handlers的基类,在它里面定义所有自Handler用到的接口并且创建一些默认的方法让子类来用(或者继承).

分享到:
评论

相关推荐

    python的logging模块

    用python写程序的,作为一个完整的项目而言,必须要有日志模块,而python的logging模块为我们提供了这么一种很好的机制,很方便的解决了这个问题。

    python的logging模块.pdf

    详解python的日志模块logging和django中对logging模块的使用

    python logging 模块

    logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点: 可以通过设置不同的日志等级,在release版本中只输出重要信息,而...

    python中logging模块

    转载于https://www.cnblogs.com/Nicholas0707/p/9021672.html,支持正版

    详解Python中logging日志模块在多进程环境下的使用

    许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行...这篇文章给大家主要介绍了在Python中logging日志模块在多进程环境下的使用,需要的朋友可以参考借鉴,下面来一起看看吧。

    python 日志 logging模块详细解析

    主要介绍了python 日志 logging模块 详细解析,本文通过实例代码给大家介绍的非常详细,对大家的工作或学习具有一定的参考借鉴价值,需要的朋友可以参考下

    Python使用logging模块实现打印log到指定文件的方法

    主要介绍了Python使用logging模块实现打印log到指定文件的方法,结合实例形式分析了Python logging模块的原理及相关日志输出操作技巧,需要的朋友可以参考下

    Python日志logging模块功能与用法详解

    本文实例讲述了Python日志logging模块功能与用法。分享给大家供大家参考,具体如下: 本文内容: logging模块的介绍 logging模块的基础使用 logging模块的扩展使用 logging中的Filter 使用配置文件配置logging...

    详解使用python的logging模块在stdout输出的两种方法

     使用python的logging模块时,除了想将日志记录在文件中外,还希望在前台执行python脚本时,可以将日志直接输出到标准输出std.out中。 实现  logging模块可以有两种方法实现该功能: 方案一:basicconfig import ...

    Python logging模块handlers用法详解

    主要介绍了Python logging模块handlers用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    Python中内置的日志模块logging用法详解

    Python的logging模块提供了通用的日志系统,可以方便第三方模块或者是应用使用。这个模块提供不同的日志级别,并可以采用不同的方式记录日志,比如文件,HTTP GET/POST,SMTP,Socket等,甚至可以自己实现具体的日志...

    python日志logging模块使用方法分析

    本文实例讲述了python日志logging模块使用方法。分享给大家供大家参考,具体如下: 一、从一个使用场景开始 开发一个日志系统, 既要把日志输出到控制台, 还要写入日志文件 import logging # 创建一个logger ...

    python logging日志模块以及多进程日志详解

    python的logging模块提供了灵活的标准模块,使得任何Python程序都可以使用这个第三方模块来实现日志记录。python logging 官方文档 logging框架中主要由四个部分组成: Loggers: 可供程序直接调用的接口 Handlers:...

    python使用logging模块发送邮件代码示例

    主要介绍了python使用logging模块发送邮件代码示例,具有一定借鉴价值,需要的朋友可以参考下

    解读python logging模块的使用方法

    logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比print,具备如下优点: 1.可以通过设置不同的日志等级,在release版本中只输出重要信息,...

    Python logging模块原理解析及应用

    主要介绍了Python logging模块原理解析及应用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Global site tag (gtag.js) - Google Analytics