16.6. 模块 "logging" --- Python 的日志记录工具
**********************************************

**源代码:** Lib/logging/__init__.py


Important
^^^^^^^^^

此页面仅包含API参考信息。有关更多高级主题的教程信息和讨论，请参阅

* 基础教程

* 进阶教程

* Logging Cookbook

======================================================================

这个模块为应用与库定义了实现灵活的事件日志系统的函数与类.

使用标准库提提供的 logging API 最主要的好处是，所有的 Python 模块都可
能参与日志输出，包括你的日志消息和第三方模块的日志消息。

这个模块提供许多强大而灵活的功能。如果你对 logging 不太熟悉的话， 掌握
它最好的方式就是查看它对应的教程（详见右侧的链接）。

该模块定义的基础类和函数都列在下面。

* 记录器暴露了应用程序代码直接使用的接口。

* 处理程序将日志记录（由记录器创建）发送到适当的目标。

* 过滤器提供了更精细的附加功能，用于确定要输出的日志记录。

* 格式化程序指定最终输出中日志记录的样式。


16.6.1. Logger 对象
===================

Loggers have the following attributes and methods.  Note that Loggers
are never instantiated directly, but always through the module-level
function "logging.getLogger(name)".  Multiple calls to "getLogger()"
with the same name will always return a reference to the same Logger
object.

"name" 是潜在的周期分割层级值, 像``foo.bar.baz`` (例如, 抛出的可以只是
明文的``foo``)。Loggers是进一步在子层次列表的更高loggers列表。例如，有
个名叫``foo``的logger，名叫``foo.bar``，"foo.bar.baz", 和 "foo.bam" 都
是 "foo``的衍生logger. logger的名字分级类似Python 包的层级, 并且相同的
如果你组织你的loggers在每模块级别基本上使用推荐的结构
``logging.getLogger(__name__)"。这是因为在模块里，在Python包的命名空间
的模块名为``__name__``。

class logging.Logger

   propagate

      如果这个属性为真，记录到这个记录器的事件将会传递给这个高级别管理
      器的记录器（原型），此外任何关联到这个记录器的管理器。消息会直接
      传递给原型记录器的管理器 - 既不是这个原型记录器的级别也不是过滤
      器是在考虑的问题。

      如果等于假，记录消息将不会传递给这个原型记录器的管理器。

      构造器将这个属性初始化为 "True"。

      注解:

        如果你关联了一个管理器*并且*到它自己的一个或多个记录器，它可能
        发出多次相同的记录。总体来说，你不需要关联管理器到一个或多个记
        录器 - 如果你只是关联它到一个合适的记录器等级中的最高级别记录
        器，它将会看到子记录器所有记录的事件，他们的传播剩下的设置为
        ``True``。一个通用场景是只关联管理器到根记录器，并且让传播照顾
        剩下的.

   setLevel(level)

      给 logger 设置阈值为 *level* 。日志等级小于 *level* 会被忽略。严
      重性为 *level* 或更高的日志消息将由该 logger 的任何一个或多个
      handler 发出，除非将处理程序的级别设置为比 *level* 更高的级别。

      创建一个 logger 时，设置级别为 "NOTSET"  （当 logger 是根 logger
      时，将处理所有消息；当 logger 是非根 logger 时，所有消息会委派给
      父级）。注意根 logger 创建时使用的是 "WARNING" 级别。

      委派给父级的意思是如果一个记录器的级别设置为NOTSET，遍历其祖先记
      录器链，直到找到另一个NOTSET级别的祖先或到达根为止。

      如果发现某个父级的级别 不是NOTSET ，那么该父级的级别将被视为发起
      搜索的记录器的有效级别，并用于确定如何处理日志事件。

      如果到达根 logger ，并且其级别为NOTSET，则将处理所有消息。否则，
      将使用根记录器的级别作为有效级别。

      参见 日志级别 级别列表。

      在 3.2 版更改: 现在 *level* 参数可以接受形如 'INFO' 的级别字符串
      表示形式，以代替形如 "INFO" 的整数常量。 但是请注意，级别在内部
      存储为整数，并且 "getEffectiveLevel()" 和 "isEnabledFor()" 等方
      法的传入/返回值也为整数。

   isEnabledFor(lvl)

      Indicates if a message of severity *lvl* would be processed by
      this logger. This method checks first the module-level level set
      by "logging.disable(lvl)" and then the logger's effective level
      as determined by "getEffectiveLevel()".

   getEffectiveLevel()

      指示此记录器的有效级别。如果通过 "setLevel()" 设置了除 "NOTSET"
      以外的值，则返回该值。否则，将层次结构遍历到根，直到找到除
      "NOTSET" 以外的其他值，然后返回该值。返回的值是一个整数，通常为
      "logging.DEBUG"、 "logging.INFO" 等等。

   getChild(suffix)

      返回由后缀确定的，是该记录器的后代的记录器。 因此，
      "logging.getLogger('abc').getChild('def.ghi')" 与
      "logging.getLogger('abc.def.ghi')" 将返回相同的记录器。 这是一个
      便捷方法，当使用如 "__name__" 而不是字符串字面值命名父记录器时很
      有用。

      3.2 新版功能.

   debug(msg, *args, **kwargs)

      Logs a message with level "DEBUG" on this logger. The *msg* is
      the message format string, and the *args* are the arguments
      which are merged into *msg* using the string formatting
      operator. (Note that this means that you can use keywords in the
      format string, together with a single dictionary argument.)

      There are three keyword arguments in *kwargs* which are
      inspected: *exc_info*, *stack_info*, and *extra*.

      如果 *exc_info* 的求值结果不为 false，则它将异常信息添加到日志消
      息中。如果提供了一个异常元组（按照 "sys.exc_info()" 返回的格式）
      或一个异常实例，则将其使用；否则，调用 "sys.exc_info()" 以获取异
      常信息。

      第二个可选关键字参数是 *stack_info*，默认为 "False"。如果为
      "True"，则将堆栈信息添加到日志消息中，包括实际的日志调用。请注意
      ，这与通过指定 *exc_info* 显示的堆栈信息不同：前者是从堆栈底部到
      当前线程中的日志记录调用的堆栈帧，而后者是在搜索异常处理程序时，
      跟踪异常而打开的堆栈帧的信息。

      您可以独立于 *exc_info* 来指定 *stack_info*，例如，即使在未引发
      任何异常的情况下，也可以显示如何到达代码中的特定点。堆栈帧在标题
      行之后打印：

         Stack (most recent call last):

      这模仿了显示异常帧时所使用的 "Traceback (most recent call
      last):" 。

      The third keyword argument is *extra* which can be used to pass
      a dictionary which is used to populate the __dict__ of the
      LogRecord created for the logging event with user-defined
      attributes. These custom attributes can then be used as you
      like. For example, they could be incorporated into logged
      messages. For example:

         FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
         logging.basicConfig(format=FORMAT)
         d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
         logger = logging.getLogger('tcpserver')
         logger.warning('Protocol problem: %s', 'connection reset', extra=d)

      输出类似于

         2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

      The keys in the dictionary passed in *extra* should not clash
      with the keys used by the logging system. (See the "Formatter"
      documentation for more information on which keys are used by the
      logging system.)

      If you choose to use these attributes in logged messages, you
      need to exercise some care. In the above example, for instance,
      the "Formatter" has been set up with a format string which
      expects 'clientip' and 'user' in the attribute dictionary of the
      LogRecord. If these are missing, the message will not be logged
      because a string formatting exception will occur. So in this
      case, you always need to pass the *extra* dictionary with these
      keys.

      尽管这可能很烦人，但此功能旨在用于特殊情况，例如在多个上下文中执
      行相同代码的多线程服务器，并且出现的有趣条件取决于此上下文（例如
      在上面的示例中就是远程客户端IP地址和已验证用户名）。在这种情况下
      ，很可能将专门的 "Formatter" 与特定的 "Handler" 一起使用。

      3.2 新版功能: 增加了 *stack_info* 参数。

      在 3.5 版更改: The *exc_info* parameter can now accept exception
      instances.

   info(msg, *args, **kwargs)

      在此记录器上记录 "INFO" 级别的消息。参数解释同 "debug()"。

   warning(msg, *args, **kwargs)

      在此记录器上记录 "WARNING" 级别的消息。参数解释同 "debug()"。

      注解:

        有一个功能上与 "warning" 一致的方法 "warn"。由于 "warn" 已被弃
        用，请不要使用它 —— 改为使用 "warning"。

   error(msg, *args, **kwargs)

      在此记录器上记录 "ERROR" 级别的消息。参数解释同 "debug()"。

   critical(msg, *args, **kwargs)

      在此记录器上记录 "CRITICAL" 级别的消息。参数解释同 "debug()"。

   log(lvl, msg, *args, **kwargs)

      Logs a message with integer level *lvl* on this logger. The
      other arguments are interpreted as for "debug()".

   exception(msg, *args, **kwargs)

      在此记录器上记录 "ERROR" 级别的消息。参数解释同 "debug()"。异常
      信息将添加到日志消息中。仅应从异常处理程序中调用此方法。

   addFilter(filter)

      将指定的过滤器 *filter* 添加到此记录器。

   removeFilter(filter)

      从此记录器中删除指定的处理程序 *filter*。

   filter(record)

      Applies this logger's filters to the record and returns a true
      value if the record is to be processed. The filters are
      consulted in turn, until one of them returns a false value. If
      none of them return a false value, the record will be processed
      (passed to handlers). If one returns a false value, no further
      processing of the record occurs.

   addHandler(hdlr)

      将指定的处理程序 *hdlr* 添加到此记录器。

   removeHandler(hdlr)

      从此记录器中删除指定的处理器 *hdlr*。

   findCaller(stack_info=False)

      查找调用源的文件名和行号，以 文件名，行号，函数名称和堆栈信息 4
      元素元组的形式返回。堆栈信息将返回 "None``除非 *stack_info* 为
      ``True"。

   handle(record)

      通过将记录传递给与此记录器及其祖先关联的所有处理器来处理（直到某
      个 *propagate* 值为 false）。此方法用于从套接字接收的未序列化的
      以及在本地创建的记录。使用 "filter()" 进行记录程序级别过滤。

   makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)

      这是一种工厂方法，可以在子类中对其进行重写以创建专门的
      "LogRecord" 实例。

   hasHandlers()

      检查此记录器是否配置了任何处理器。通过在此记录器及其记录器层次结
      构中的父级中查找处理器完成此操作。如果找到处理器则返回 "True"，
      否则返回``False``。只要找到 “propagate” 属性设置为 false的记录器
      ，该方法就会停止搜索层次结构 —— 其将是最后一个检查处理器是否存在
      的记录器。

      3.2 新版功能.

   在 3.7 版更改: Loggers can now be picked and unpickled.


16.6.2. 日志级别
================

日志记录级别的数值在下表中给出。如果你想要定义自己的级别，并且需要它们
具有相对于预定义级别的特定值，那么这些内容可能是你感兴趣的。如果你定义
具有相同数值的级别，它将覆盖预定义的值; 预定义的名称丢失。

+----------------+-----------------+
| 级别           | 数值            |
|================|=================|
| "CRITICAL"     | 50              |
+----------------+-----------------+
| "ERROR"        | 40              |
+----------------+-----------------+
| "WARNING"      | 30              |
+----------------+-----------------+
| "INFO"         | 20              |
+----------------+-----------------+
| "DEBUG"        | 10              |
+----------------+-----------------+
| "NOTSET"       | 0               |
+----------------+-----------------+


16.6.3. 处理器对象
==================

Handler 有以下属性和方法。注意不要直接实例化 "Handler" ；这个类用来派
生其他更有用的子类。但是，子类的 "__init__()" 方法需要调用
"Handler.__init__()" 。

class logging.Handler

   __init__(level=NOTSET)

      初始化 "Handler" 实例时，需要设置它的级别，将过滤列表置为空，并
      且创建锁（通过 "createLock()" ）来序列化对 I/O 的访问。

   createLock()

      初始化一个线程锁，用来序列化对底层的 I/O 功能的访问，底层的 I/O
      功能可能不是线程安全的。

   acquire()

      使用 "createLock()"  获取线程锁。

   release()

      使用 "acquire()" 来释放线程锁。

   setLevel(level)

      给处理器设置阈值为 *level* 。日志级别小于 *level* 将被忽略。创建
      处理器时，日志级别被设置为 "NOTSET" （所有的消息都会被处理）。

      参见 日志级别 级别列表。

      在 3.2 版更改: *level* 形参现在接受像 'INFO' 这样的字符串形式的
      级别表达方式，也可以使用像 "INFO" 这样的整数常量。

   setFormatter(fmt)

      将此处理器的 "Formatter" 设置为 *fmt*。

   addFilter(filter)

      将指定的过滤器 *filter* 添加到此处理器。

   removeFilter(filter)

      从此处理器中删除指定的过滤器 *filter* 。

   filter(record)

      Applies this handler's filters to the record and returns a true
      value if the record is to be processed. The filters are
      consulted in turn, until one of them returns a false value. If
      none of them return a false value, the record will be emitted.
      If one returns a false value, the handler will not emit the
      record.

   flush()

      确保所有日志记录从缓存输出。此版本不执行任何操作，并且应由子类实
      现。

   close()

      整理处理器使用的所有资源。此版本不输出，但从内部处理器列表中删除
      处理器，内部处理器在 "shutdown()" 被调用时关闭 。子类应确保从重
      写的 "close()" 方法中调用此方法。

   handle(record)

      经已添加到处理器的过滤器过滤后，有条件地发出指定的日志记录。用获
      取/释放 I/O 线程锁包装记录的实际发出行为。

   handleError(record)

      调用 "emit()" 期间遇到异常时，应从处理器中调用此方法。如果模块级
      属性 "raiseExceptions" 是 "False"，则异常将被静默忽略。这是大多
      数情况下日志系统需要的 —— 大多数用户不会关心日志系统中的错误，他
      们对应用程序错误更感兴趣。但是，你可以根据需要将其替换为自定义处
      理器。指定的记录是发生异常时正在处理的记录。（"raiseExceptions"
      的默认值是 "True"，因为这在开发过程中是比较有用的）。

   format(record)

      如果设置了格式器则用其对记录进行格式化。否则，使用模块的默认格式
      器。

   emit(record)

      执行实际记录给定日志记录所需的操作。这个版本应由子类实现，因此这
      里直接引发 "NotImplementedError" 异常。

有关作为标准随附的处理程序，请参见 "logging.handlers"。


16.6.4. 格式器对象
==================

"Formatter" 对象拥有以下的属性和方法。一般情况下，它们负责将
"LogRecord" 转换为可由人或外部系统解释的字符串。基础的 "Formatter" 允
许指定格式字符串。如果未提供任何值，则使用默认值 "'%(message)s'" ，它
仅将消息包括在日志记录调用中。要在格式化输出中包含其他信息（如时间戳）
，请阅读下文。

格式器可以使用格式化字符串来初始化，该字符串利用 "LogRecord" 的属性 ——
例如上述默认值，用户的消息和参数预先格式化为 "LogRecord" 的 *message*
属性后被使用。此格式字符串包含标准的 Python %-s 样式映射键。有关字符串
格式的更多信息，请参见 printf 风格的字符串格式化。

The useful mapping keys in a "LogRecord" are given in the section on
LogRecord 属性.

class logging.Formatter(fmt=None, datefmt=None, style='%')

   返回 "Formatter" 类的新实例。实例将使用整个消息的格式字符串以及消息
   的日期/时间部分的格式字符串进行初始化。如果未指定 *fmt* ，则使用
   "'%(message)s'"。如果未指定 *datefmt*，则使用  "formatTime()" 文档
   中描述的格式。

   The *style* parameter can be one of '%', '{' or '$' and determines
   how the format string will be merged with its data: using one of
   %-formatting, "str.format()" or "string.Template". See Using
   particular formatting styles throughout your application for more
   information on using {- and $-formatting for log messages.

   在 3.2 版更改: *style*  参数已加入.

   format(record)

      记录的属性字典用作字符串格式化操作的参数。返回结果字符串。在格式
      化字典之前，需要执行几个准备步骤。 使用 *msg* % *args* 计算记录
      的 *message* 属性。如果格式化字符串包含 "'(asctime)'"，则调用
      "formatTime()" 来格式化事件时间。如果有异常信息，则使用
      "formatException()" 将其格式化并附加到消息中。请注意，格式化的异
      常信息缓存在属性 *exc_text* 中。这很有用，因为可以对异常信息进行
      序列化并通过网络发送，但是如果您有不止一个定制了异常信息格式的
      "Formatter" 子类，则应格外小心。在这种情况下，您必须在格式器完成
      格式化后清除缓存的值，以便下一个处理事件的格式化程序不使用缓存的
      值，而是重新计算它。

      如果栈信息可用，它将被添加在异常信息之后，如有必要请使用
      "formatStack()" 来转换它。

   formatTime(record, datefmt=None)

      此方法应由想要使用格式化时间的格式器中的 "format()" 调用。可以在
      格式器中重写此方法以提供任何特定要求，但是基本行为如下：如果指定
      了 *datefmt* （字符串），则将其用于 "time.strftime()" 来格式化记
      录的创建时间。否则，使用格式 '%Y-%m-%d %H:%M:%S,uuu'，其中 uuu
      部分是毫秒值，其他字母根据 "time.strftime()" 文档。这种时间格式
      的示例为 "2003-01-23 00:29:50,411"。返回结果字符串。

      此函数使用一个用户可配置函数将创建时间转换为元组。 默认情况下，
      使用 "time.localtime()"；要为特定格式化程序实例更改此项，请将实
      例的 "converter" 属性设为具有与 "time.localtime()" 或
      "time.gmtime()" 相同签名的函数。 要为所有格式化程序更改此项，例
      如当你希望所有日志时间都显示为 GMT，请在 "Formatter" 类中设置
      "converter" 属性。

      在 3.3 版更改: 在之前版本中，默认格式为写死的代码，例如这个例子:
      "2010-09-06 22:38:15,292" 其中逗号之前的部分由 strptime 格式字符
      串 ("'%Y-%m-%d %H:%M:%S'") 处理，而逗号之后的部分为毫秒值。 因为
      strptime 没有表示毫秒的占位符，毫秒值使用了另外的格式字符串来添
      加 "'%s,%03d'" --- 这两个格式字符串代码都是写死在该方法中的。 经
      过修改，这些字符串被定义为类层级的属性，当需要时可以在实例层级上
      被重载。 属性的名称为 "default_time_format" (用于 strptime 格式
      字符串) 和 "default_msec_format" (用于添加毫秒值)。

   formatException(exc_info)

      将指定的异常信息（由 "sys.exc_info()" 返回的标准异常元组）格式化
      为字符串。 这个默认实现只使用了 "traceback.print_exception()"。
      结果字符串将被返回。

   formatStack(stack_info)

      将指定的堆栈信息（由 "traceback.print_stack()" 返回的字符串，但
      移除末尾的换行符）格式化为字符串。 这个默认实现只是返回输入值。


16.6.5. Filter 对象
===================

"Filters" 可被 "Handlers" 和 "Loggers" 用来实现比按层级提供更复杂的过
滤操作。 基本过滤器类只允许低于日志记录器层级结构中低于特定层级的事件
。 例如，一个用 'A.B' 初始化的过滤器将允许 'A.B', 'A.B.C', 'A.B.C.D',
'A.B.D' 等日志记录器所记录的事件。 但 'A.BB', 'B.A.B' 等则不允许。 如
果用空字符串初始化，则所有事件都会被略过。

class logging.Filter(name='')

   返回一个 "Filter" 类的实例。 如果指定了 *name*，则它将被用来为日志
   记录器命名，该类及其子类将通过该过滤器允许指定事件通过。 如果
   *name* 为空字符串，则允许所有事件通过。

   filter(record)

      是否要记录指定的记录？返回零表示否，非零表示是。如果认为合适，则
      可以通过此方法就地修改记录。

请注意关联到处理程序的过滤器会在事件由处理程序发出之前被查询，而关联到
日志记录器的过滤器则会在有事件被记录的的任何时候（使用 "debug()",
"info()" 等等）在将事件发送给处理程序之前被查询。 这意味着由后代日志记
录器生成的事件将不会被日志记录器的过滤器设置所过滤，除非该过滤器也已被
应用于后代日志记录器。

你实际上不需要子类化 "Filter": 你可以将传入任何包含 "filter" 方法的具
有相同语义的的实例。

在 3.2 版更改: 你不需要创建专门的 "Filter" 类，或使用具有 "filter" 方
法的其他类：你可以使用一个函数（或其他可调用对象）作为过滤器。 过滤逻
辑将检查过滤器对象是否文化的 "filter" 属性：如果有，就会将它当作是
"Filter" 并调用它的 "filter()" 方法。 在其他情况下，则会将它当作是可调
用对象并附带记录作为单一形参进行调用。 返回值应当与 "filter()" 的返回
值相一致。

Although filters are used primarily to filter records based on more
sophisticated criteria than levels, they get to see every record which
is processed by the handler or logger they're attached to: this can be
useful if you want to do things like counting how many records were
processed by a particular logger or handler, or adding, changing or
removing attributes in the LogRecord being processed. Obviously
changing the LogRecord needs to be done with some care, but it does
allow the injection of contextual information into logs (see 使用过滤
器传递上下文信息).


16.6.6. LogRecord 属性
======================

"LogRecord" 实例是每当有日志被记录时由 "Logger" 自动创建的，并且可通过
"makeLogRecord()" 手动创建（例如根据从网络接收的已封存事件创建）。

class logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)

   包含与被记录的事件相关的所有信息。

   主要信息是在 "msg" 和 "args" 中传递的，它们使用 "msg % args" 组合到
   一起以创建记录的 "message" 字段。

   参数:
      * **name** -- 用于记录由此 LogRecord 所表示 的事件的日志记录器名
        称。 请注意此名称将始终为该值，即使它可以是由附加到不同（祖先
        ）日志记录器的处理程序所发出的。

      * **level** -- 以数字表示的日志记录事件层级（如 DEBUG, INFO 等）
        。 请注意这会转换为 LogRecord 的 *两个* 属性: "levelno" 为数字
        值而 "levelname" 为对应的层级名称。

      * **pathname** -- 进行日志记录调用的文件的完整路径名。

      * **lineno** -- 记录调用所在源文件中的行号。

      * **msg** -- 事件描述消息，可能为带有可变数据占位符的格式字符串
        。

      * **args** -- 要合并到 *msg* 参数以获得事件描述的可变数据。

      * **exc_info** -- 包含当前异常信息的异常元组，或者如果没有可用异
        常信息则为 "None"。

      * **func** -- 发起调用日志记录调用的函数或方法名称。

      * **sinfo** -- 一个文本字符串，表示当前线程中从堆栈底部直到日志
        记录调用的堆栈信息。

   getMessage()

      在将 "LogRecord" 实例与任何用户提供的参数合并之后，返回此实例的
      消息。 如果用户提供给日志记录调用的消息参数不是字符串，则会在其
      上调用 "str()" 以将它转换为字符串。 此方法允许将用户定义的类用作
      消息，类的 "__str__" 方法可以返回要使用的实际格式字符串。

   在 3.2 版更改: The creation of a "LogRecord" has been made more
   configurable by providing a factory which is used to create the
   record. The factory can be set using "getLogRecordFactory()" and
   "setLogRecordFactory()" (see this for the factory's signature).

   This functionality can be used to inject your own values into a
   LogRecord at creation time. You can use the following pattern:

      old_factory = logging.getLogRecordFactory()

      def record_factory(*args, **kwargs):
          record = old_factory(*args, **kwargs)
          record.custom_attribute = 0xdecafbad
          return record

      logging.setLogRecordFactory(record_factory)

   通过此模式，多个工厂方法可以被链接起来，并且只要它们不重载彼此的属
   性或是在无意中覆盖了上面列出的标准属性，就不会发生意外。


16.6.7. LogRecord 属性
======================

LogRecord 具有许多属性，它们大多数来自于传递给构造器的形参。 （请注意
LogRecord 构造器形参与 LogRecord 属性的名称并不总是完全彼此对应的。）
这些属性可被用于将来自记录的数据合并到格式字符串中。 下面的表格（按字
母顺序）列出了属性名称、它们的含义以及相应的 %-style 格式字符串内占位
符。

如果是使用 {}-格式化 ("str.format()")，你可以将 "{attrname}" 用作格式
字符串内的占位符。 如果是使用 $-格式化 ("string.Template")，则会使用
"${attrname}" 的形式。 当然在这两种情况下，都应当将 "attrname" 替换为
你想要使用的实际属性名称。

在 {}-格式化的情况下，你可以在属性名称之后放置指定的格式化旗标，并用冒
号来分隔两者。 例如，占位符 "{msecs:03d}" 会将毫秒值 "4" 格式化为
"004"。 请参看 "str.format()" 文档了解你所能使用的选项的完整细节。

+------------------+---------------------------+-------------------------------------------------+
| 属性名称         | 格式                      | 描述                                            |
|==================|===========================|=================================================|
| args             | 不需要格式化。            | 合并到 "msg" 以产生 "message" 的包含参数的元组  |
|                  |                           | ，或是其中的值将被用于合 并的字典（当只有一个参 |
|                  |                           | 数且其类型为字典时）。                          |
+------------------+---------------------------+-------------------------------------------------+
| asctime          | "%(asctime)s"             | 表示 "LogRecord" 何时被创建的供人查看时间值。   |
|                  |                           | 默认形式为 '2003-07-08 16:49:45,896' (逗号之后  |
|                  |                           | 的数字为时间的毫秒部分)。                       |
+------------------+---------------------------+-------------------------------------------------+
| created          | "%(created)f"             | "LogRecord" 被创建的时间（即 "time.time()" 的返 |
|                  |                           | 回值）。                                        |
+------------------+---------------------------+-------------------------------------------------+
| exc_info         | 不需要格式化。            | 异常元组 (例如 "sys.exc_info") 或者如未发生异常 |
|                  |                           | 则为 "None"。                                   |
+------------------+---------------------------+-------------------------------------------------+
| filename         | "%(filename)s"            | "pathname" 的文件名部分。                       |
+------------------+---------------------------+-------------------------------------------------+
| funcName         | "%(funcName)s"            | 函数名包括调用日志记录.                         |
+------------------+---------------------------+-------------------------------------------------+
| levelname        | "%(levelname)s"           | 消息文本记录级别 ("'DEBUG'", "'INFO'",          |
|                  |                           | "'WARNING'", "'ERROR'", "'CRITICAL'").          |
+------------------+---------------------------+-------------------------------------------------+
| levelno          | "%(levelno)s"             | 消息数字记录级别 ("DEBUG", "INFO", "WARNING",   |
|                  |                           | "ERROR", "CRITICAL").                           |
+------------------+---------------------------+-------------------------------------------------+
| lineno           | "%(lineno)d"              | 发出日志记录调用所在的源行号（如果可用）。      |
+------------------+---------------------------+-------------------------------------------------+
| message          | "%(message)s"             | 记入日志的消息，即 "msg % args" 的结果。 这是在 |
|                  |                           | 发起调用 "Formatter.format()" 时设置的。        |
+------------------+---------------------------+-------------------------------------------------+
| module 模块      | "%(module)s"              | 模块 ("filename" 的名称部分)。                  |
+------------------+---------------------------+-------------------------------------------------+
| msecs            | "%(msecs)d"               | "LogRecord" 被创建的时间的毫秒部分。            |
+------------------+---------------------------+-------------------------------------------------+
| msg              | 不需要格式化。            | 在原始日志记录调用中传入的格式字符串。 与       |
|                  |                           | "args" 合并以产生 "message" ，或是一个任意对象  |
|                  |                           | (参见 使用任意对象作为消息)。                   |
+------------------+---------------------------+-------------------------------------------------+
| 名称             | "%(name)s"                | 用于记录调用的日志记录器名称。                  |
+------------------+---------------------------+-------------------------------------------------+
| pathname         | "%(pathname)s"            | 发出日志记录调用的源文件的完整路径名（如果可用  |
|                  |                           | ）。                                            |
+------------------+---------------------------+-------------------------------------------------+
| process          | "%(process)d"             | 进程ID（如果可用）                              |
+------------------+---------------------------+-------------------------------------------------+
| processName      | "%(processName)s"         | 进程名（如果可用）                              |
+------------------+---------------------------+-------------------------------------------------+
| relativeCreated  | "%(relativeCreated)d"     | 以毫秒数表示的 LogRecord 被创建的时间，即相对于 |
|                  |                           | logging 模块被加载时间 的差值。                 |
+------------------+---------------------------+-------------------------------------------------+
| stack_info       | 不需要格式化。            | 当前线程中从堆栈底部起向上直到包括日志记录调用  |
|                  |                           | 并导致创建此记录的堆栈帧 的堆栈帧信息（如果可用 |
|                  |                           | ）。                                            |
+------------------+---------------------------+-------------------------------------------------+
| thread           | "%(thread)d"              | 线程ID（如果可用）                              |
+------------------+---------------------------+-------------------------------------------------+
| threadName       | "%(threadName)s"          | 线程名（如果可用）                              |
+------------------+---------------------------+-------------------------------------------------+

在 3.1 版更改: 添加了 *processName*


16.6.8. LoggerAdapter 对象
==========================

"LoggerAdapter" 实例会被用来方便地将上下文信息传入日志记录调用。 要获
取用法示例，请参阅 添加上下文信息到你的日志记录输出 部分。

class logging.LoggerAdapter(logger, extra)

   返回一个 "LoggerAdapter" 的实例，该实例的初始化带有一个下层的
   "Logger" 实例和一个字典类对象。

   process(msg, kwargs)

      修改传递给日志记录调用的消息和/或关键字参数以便插入上下文信息。
      此实现接受以 *extra* 形式传给构造器的对象并使用 'extra' 键名将其
      加入 *kwargs*。 返回值为一个 (*msg*, *kwargs*) 元组，其中传入了
      （可能经过修改的）参数版本。

在上述方法之外，"LoggerAdapter" 还支持 "Logger" 的下列方法: "debug()",
"info()", "warning()", "error()", "exception()", "critical()",
"log()", "isEnabledFor()", "getEffectiveLevel()", "setLevel()" 以及
"hasHandlers()"。 这些方法具有与它们在 "Logger" 中的对应方法相同的签名
，因此你可以互换使用这两种类型的实例。

在 3.2 版更改: "isEnabledFor()", "getEffectiveLevel()", "setLevel()"
和 "hasHandlers()" 方法已被添加到 "LoggerAdapter"。 这些方法会委托给下
层的日志记录器。


16.6.9. 线程安全
================

logging 模块的目标是使客户端不必执行任何特殊操作即可确保线程安全。 它
通过使用线程锁来达成这个目标；用一个锁来序列化对模块共享数据的访问，并
且每个处理程序也会创建一个锁来序列化对其下层 I/O 的访问。

如果你要使用 "signal" 模块来实现异步信号处理程序，则可能无法在这些处理
程序中使用 logging。 这是因为 "threading" 模块中的锁实现并非总是可重入
的，所以无法从此类信号处理程序发起调用。


16.6.10. 模块级别函数
=====================

在上述的类之外，还有一些模块层级的函数。

logging.getLogger(name=None)

   Return a logger with the specified name or, if name is "None",
   return a logger which is the root logger of the hierarchy. If
   specified, the name is typically a dot-separated hierarchical name
   like *'a'*, *'a.b'* or *'a.b.c.d'*. Choice of these names is
   entirely up to the developer who is using logging.

   All calls to this function with a given name return the same logger
   instance. This means that logger instances never need to be passed
   between different parts of an application.

logging.getLoggerClass()

   Return either the standard "Logger" class, or the last class passed
   to "setLoggerClass()". This function may be called from within a
   new class definition, to ensure that installing a customized
   "Logger" class will not undo customizations already applied by
   other code. For example:

      class MyLogger(logging.getLoggerClass()):
          # ... override behaviour here

logging.getLogRecordFactory()

   Return a callable which is used to create a "LogRecord".

   3.2 新版功能: This function has been provided, along with
   "setLogRecordFactory()", to allow developers more control over how
   the "LogRecord" representing a logging event is constructed.

   See "setLogRecordFactory()" for more information about the how the
   factory is called.

logging.debug(msg, *args, **kwargs)

   Logs a message with level "DEBUG" on the root logger. The *msg* is
   the message format string, and the *args* are the arguments which
   are merged into *msg* using the string formatting operator. (Note
   that this means that you can use keywords in the format string,
   together with a single dictionary argument.)

   There are three keyword arguments in *kwargs* which are inspected:
   *exc_info* which, if it does not evaluate as false, causes
   exception information to be added to the logging message. If an
   exception tuple (in the format returned by "sys.exc_info()") or an
   exception instance is provided, it is used; otherwise,
   "sys.exc_info()" is called to get the exception information.

   第二个可选关键字参数是 *stack_info*，默认为 "False"。如果为 "True"
   ，则将堆栈信息添加到日志消息中，包括实际的日志调用。请注意，这与通
   过指定 *exc_info* 显示的堆栈信息不同：前者是从堆栈底部到当前线程中
   的日志记录调用的堆栈帧，而后者是在搜索异常处理程序时，跟踪异常而打
   开的堆栈帧的信息。

   您可以独立于 *exc_info* 来指定 *stack_info*，例如，即使在未引发任何
   异常的情况下，也可以显示如何到达代码中的特定点。堆栈帧在标题行之后
   打印：

      Stack (most recent call last):

   这模仿了显示异常帧时所使用的 "Traceback (most recent call last):"
   。

   The third optional keyword argument is *extra* which can be used to
   pass a dictionary which is used to populate the __dict__ of the
   LogRecord created for the logging event with user-defined
   attributes. These custom attributes can then be used as you like.
   For example, they could be incorporated into logged messages. For
   example:

      FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
      logging.basicConfig(format=FORMAT)
      d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
      logging.warning('Protocol problem: %s', 'connection reset', extra=d)

   would print something like:

      2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

   The keys in the dictionary passed in *extra* should not clash with
   the keys used by the logging system. (See the "Formatter"
   documentation for more information on which keys are used by the
   logging system.)

   If you choose to use these attributes in logged messages, you need
   to exercise some care. In the above example, for instance, the
   "Formatter" has been set up with a format string which expects
   'clientip' and 'user' in the attribute dictionary of the LogRecord.
   If these are missing, the message will not be logged because a
   string formatting exception will occur. So in this case, you always
   need to pass the *extra* dictionary with these keys.

   尽管这可能很烦人，但此功能旨在用于特殊情况，例如在多个上下文中执行
   相同代码的多线程服务器，并且出现的有趣条件取决于此上下文（例如在上
   面的示例中就是远程客户端IP地址和已验证用户名）。在这种情况下，很可
   能将专门的 "Formatter" 与特定的 "Handler" 一起使用。

   3.2 新版功能: 增加了 *stack_info* 参数。

logging.info(msg, *args, **kwargs)

   Logs a message with level "INFO" on the root logger. The arguments
   are interpreted as for "debug()".

logging.warning(msg, *args, **kwargs)

   Logs a message with level "WARNING" on the root logger. The
   arguments are interpreted as for "debug()".

   注解:

     There is an obsolete function "warn" which is functionally
     identical to "warning". As "warn" is deprecated, please do not
     use it - use "warning" instead.

logging.error(msg, *args, **kwargs)

   Logs a message with level "ERROR" on the root logger. The arguments
   are interpreted as for "debug()".

logging.critical(msg, *args, **kwargs)

   Logs a message with level "CRITICAL" on the root logger. The
   arguments are interpreted as for "debug()".

logging.exception(msg, *args, **kwargs)

   Logs a message with level "ERROR" on the root logger. The arguments
   are interpreted as for "debug()". Exception info is added to the
   logging message. This function should only be called from an
   exception handler.

logging.log(level, msg, *args, **kwargs)

   Logs a message with level *level* on the root logger. The other
   arguments are interpreted as for "debug()".

   注解:

     The above module-level convenience functions, which delegate to
     the root logger, call "basicConfig()" to ensure that at least one
     handler is available. Because of this, they should *not* be used
     in threads, in versions of Python earlier than 2.7.1 and 3.2,
     unless at least one handler has been added to the root logger
     *before* the threads are started. In earlier versions of Python,
     due to a thread safety shortcoming in "basicConfig()", this can
     (under rare circumstances) lead to handlers being added multiple
     times to the root logger, which can in turn lead to multiple
     messages for the same event.

logging.disable(lvl=CRITICAL)

   Provides an overriding level *lvl* for all loggers which takes
   precedence over the logger's own level. When the need arises to
   temporarily throttle logging output down across the whole
   application, this function can be useful. Its effect is to disable
   all logging calls of severity *lvl* and below, so that if you call
   it with a value of INFO, then all INFO and DEBUG events would be
   discarded, whereas those of severity WARNING and above would be
   processed according to the logger's effective level. If
   "logging.disable(logging.NOTSET)" is called, it effectively removes
   this overriding level, so that logging output again depends on the
   effective levels of individual loggers.

   Note that if you have defined any custom logging level higher than
   "CRITICAL" (this is not recommended), you won't be able to rely on
   the default value for the *lvl* parameter, but will have to
   explicitly supply a suitable value.

   在 3.7 版更改: The *lvl* parameter was defaulted to level
   "CRITICAL". See Issue #28524 for more information about this
   change.

logging.addLevelName(lvl, levelName)

   Associates level *lvl* with text *levelName* in an internal
   dictionary, which is used to map numeric levels to a textual
   representation, for example when a "Formatter" formats a message.
   This function can also be used to define your own levels. The only
   constraints are that all levels used must be registered using this
   function, levels should be positive integers and they should
   increase in increasing order of severity.

   注解:

     If you are thinking of defining your own levels, please see the
     section on 自定义级别.

logging.getLevelName(lvl)

   Returns the textual representation of logging level *lvl*. If the
   level is one of the predefined levels "CRITICAL", "ERROR",
   "WARNING", "INFO" or "DEBUG" then you get the corresponding string.
   If you have associated levels with names using "addLevelName()"
   then the name you have associated with *lvl* is returned. If a
   numeric value corresponding to one of the defined levels is passed
   in, the corresponding string representation is returned. Otherwise,
   the string 'Level %s' % lvl is returned.

   注解:

     Levels are internally integers (as they need to be compared in
     the logging logic). This function is used to convert between an
     integer level and the level name displayed in the formatted log
     output by means of the "%(levelname)s" format specifier (see
     LogRecord 属性).

   在 3.4 版更改: In Python versions earlier than 3.4, this function
   could also be passed a text level, and would return the
   corresponding numeric value of the level. This undocumented
   behaviour was considered a mistake, and was removed in Python 3.4,
   but reinstated in 3.4.2 due to retain backward compatibility.

logging.makeLogRecord(attrdict)

   Creates and returns a new "LogRecord" instance whose attributes are
   defined by *attrdict*. This function is useful for taking a pickled
   "LogRecord" attribute dictionary, sent over a socket, and
   reconstituting it as a "LogRecord" instance at the receiving end.

logging.basicConfig(**kwargs)

   Does basic configuration for the logging system by creating a
   "StreamHandler" with a default "Formatter" and adding it to the
   root logger. The functions "debug()", "info()", "warning()",
   "error()" and "critical()" will call "basicConfig()" automatically
   if no handlers are defined for the root logger.

   This function does nothing if the root logger already has handlers
   configured for it.

   注解:

     This function should be called from the main thread before other
     threads are started. In versions of Python prior to 2.7.1 and
     3.2, if this function is called from multiple threads, it is
     possible (in rare circumstances) that a handler will be added to
     the root logger more than once, leading to unexpected results
     such as messages being duplicated in the log.

   支持以下关键字参数。

   +----------------+-----------------------------------------------+
   | 格式           | 描述                                          |
   |================|===============================================|
   | *filename*     | 使用指定的文件名而不是 StreamHandler 创建     |
   |                | FileHandler。                                 |
   +----------------+-----------------------------------------------+
   | *filemode*     | 如果指定了 *filename*，则用此 模式 打开该文件 |
   |                | 。 默认模式为 "'a'"。                         |
   +----------------+-----------------------------------------------+
   | *format*       | 处理器使用的指定格式字符串。                  |
   +----------------+-----------------------------------------------+
   | *datefmt*      | Use the specified date/time format, as        |
   |                | accepted by "time.strftime()".                |
   +----------------+-----------------------------------------------+
   | *style*        | If *format* is specified, use this style for  |
   |                | the format string. One of "'%'", "'{'" or     |
   |                | "'$'" for printf-style, "str.format()" or     |
   |                | "string.Template" respectively. Defaults to   |
   |                | "'%'".                                        |
   +----------------+-----------------------------------------------+
   | *level*        | 设置根记录器级别去指定 level.                 |
   +----------------+-----------------------------------------------+
   | *stream*       | 使用指定的流初始化 StreamHandler。 请注意此参 |
   |                | 数与 *filename* 是不兼 容的 - 如果两者同时存  |
   |                | 在，则会引发 "ValueError"。                   |
   +----------------+-----------------------------------------------+
   | *handlers*     | If specified, this should be an iterable of   |
   |                | already created handlers to add to the root   |
   |                | logger. Any handlers which don't already have |
   |                | a formatter set will be assigned the default  |
   |                | formatter created in this function. Note that |
   |                | this argument is incompatible with *filename* |
   |                | or *stream* - if both are present, a          |
   |                | "ValueError" is raised.                       |
   +----------------+-----------------------------------------------+

   在 3.2 版更改: 增加了 *style* 参数。

   在 3.3 版更改: The *handlers* argument was added. Additional checks
   were added to catch situations where incompatible arguments are
   specified (e.g. *handlers* together with *stream* or *filename*, or
   *stream* together with *filename*).

logging.shutdown()

   Informs the logging system to perform an orderly shutdown by
   flushing and closing all handlers. This should be called at
   application exit and no further use of the logging system should be
   made after this call.

logging.setLoggerClass(klass)

   Tells the logging system to use the class *klass* when
   instantiating a logger. The class should define "__init__()" such
   that only a name argument is required, and the "__init__()" should
   call "Logger.__init__()". This function is typically called before
   any loggers are instantiated by applications which need to use
   custom logger behavior.

logging.setLogRecordFactory(factory)

   Set a callable which is used to create a "LogRecord".

   参数:
      **factory** -- The factory callable to be used to instantiate a
      log record.

   3.2 新版功能: This function has been provided, along with
   "getLogRecordFactory()", to allow developers more control over how
   the "LogRecord" representing a logging event is constructed.

   The factory has the following signature:

   "factory(name, level, fn, lno, msg, args, exc_info, func=None,
   sinfo=None, **kwargs)"

      名称:
         日志记录器名称

      level:
         日志记录级别（数字）。

      fn:
         进行日志记录调用的文件的完整路径名。

      lno:
         记录调用所在文件中的行号。

      msg:
         日志消息。

      args:
         日志记录消息的参数。

      exc_info:
         异常元组，或 "None" 。

      func:
         调用日志记录调用的函数或方法的名称。

      sinfo:
         A stack traceback such as is provided by
         "traceback.print_stack()", showing the call hierarchy.

      kwargs:
         其他关键字参数。


16.6.11. 模块级属性
===================

logging.lastResort

   A "handler of last resort" is available through this attribute.
   This is a "StreamHandler" writing to "sys.stderr" with a level of
   "WARNING", and is used to handle logging events in the absence of
   any logging configuration. The end result is to just print the
   message to "sys.stderr". This replaces the earlier error message
   saying that "no handlers could be found for logger XYZ". If you
   need the earlier behaviour for some reason, "lastResort" can be set
   to "None".

   3.2 新版功能.


16.6.12. 与警告模块集成
=======================

"captureWarnings()" 函数可用来将 "logging" 和 "warnings" 模块集成。

logging.captureWarnings(capture)

   此函数用于打开和关闭日志系统对警告的捕获。

   如果 *capture* 是 "True"，则 "warnings" 模块发出的警告将重定向到日
   志记录系统。具体来说，将使用 "warnings.formatwarning()" 格式化警告
   信息，并将结果字符串使用 "WARNING" 等级记录到名为 "'py.warnings'"
   的记录器中。

   如果 *capture* 是 "False"，则将停止将警告重定向到日志记录系统，并且
   将警告重定向到其原始目标（即在  "captureWarnings(True)"  调用之前的
   有效目标）。

参见:

  模块 "logging.config"
     日志记录模块的配置 API 。

  模块 "logging.handlers"
     日志记录模块附带的有用处理程序。

  **PEP 282** - Logging 系统
     该提案描述了Python标准库中包含的这个特性。

  Original Python logging package
     这是该 "logging" 包的原始来源。该站点提供的软件包版本适用于
     Python 1.5.2、2.1.x 和 2.2.x，它们不被 "logging" 包含在标准库中。
