# `logging.handlers` --- 日志处理程序

源代码: Lib/logging/handlers.py

这个包提供了以下有用的处理程序。 请注意有三个处理程序类 (`StreamHandler`, `FileHandler` 和 `NullHandler`) 实际上是在 `logging` 模块本身定义的，但其文档与其他处理程序一同记录在此。

## StreamHandler

`StreamHandler` 类位于核心 `logging` 包，它可将日志记录输出发送到数据流例如 sys.stdout, sys.stderr 或任何文件类对象（或者更精确地说，任何支持 `write()` 和 `flush()` 方法的对象）。

class `logging.``StreamHandler`(stream=None)

  返回一个新的 `StreamHandler` 类。 如果指定了 stream，则实例将用它作为日志记录输出；在其他情况下将使用 sys.stderr。

  `emit`(record)

    如果指定了一个格式化器，它会被用来格式化记录。 随后记录会被写入到 `terminator` 之后的流中。 如果存在异常信息，则会使用 `traceback.print_exception()` 来格式化并添加到流中。

  `flush`()

    通过调用流的 `flush()` 方法来刷新它。 请注意 `close()` 方法是继承自 `Handler` 的所以没有输出，因此有时可能需要显式地调用 `flush()`。

  `setStream`(stream)

    将实例的流设为指定值，如果两者不一致的话。 旧的流会在设置新的流之前被刷新。

    参数

      stream -- 处理程序应当使用的流。

    返回

      旧的流，如果流已被改变的话，如果未被改变则为 None。

    3.7 新版功能.

  `terminator`

    当将已格式化的记录写入到流时被用作终止符的字符串。 默认值为 `'\n'`。

    如果你不希望以换行符终止，你可以将处理程序类实例的 `terminator` 属性设为空字符串。

    在较早的版本中，终止符被硬编码为 `'\n'`。

    3.2 新版功能.

## FileHandler

`FileHandler` 类位于核心 `logging` 包，它可将日志记录输出到磁盘文件中。 它从 `StreamHandler` 继承了输出功能。

class `logging.``FileHandler`(filename, mode='a', encoding=None, delay=False, errors=None)

  返回一个 `FileHandler` 类的新实例。 将打开指定的文件并将其用作日志记录流。 如果未指定 mode，则会使用 `'a'`。 如果 encoding 不为 `None`，则会将其用作打开文件的编码格式。 如果 delay 为真值，则文件打开会被推迟至第一次调用 `emit()` 时。 默认情况下，文件会无限增长。 如果指定了 errors，它会被用于确定编码格式错误的处理方式。

  在 3.6 版更改: 除了字符串值，也接受 `Path` 对象作为 filename 参数。

  在 3.9 版更改: 增加了 errors 形参。

  `close`()

    关闭文件。

  `emit`(record)

    将记录输出到文件。

## NullHandler

3.1 新版功能.

`NullHandler` 类位于核心 `logging` 包，它不执行任何格式化或输出。 它实际上是一个供库开发者使用的‘无操作’处理程序。

class `logging.``NullHandler`

  返回一个 `NullHandler` 类的新实例。

  `emit`(record)

    此方法不执行任何操作。

  `handle`(record)

    此方法不执行任何操作。

  `createLock`()

    此方法会对锁返回 `None`，因为没有下层 I/O 的访问需要被序列化。

请参阅 配置库的日志记录 了解有关如何使用 `NullHandler` 的更多信息。

## WatchedFileHandler

`WatchedFileHandler` 类位于 `logging.handlers` 模块，这个 `FileHandler` 用于监视它所写入日志记录的文件。 如果文件发生变化，它会被关闭并使用文件名重新打开。

发生文件更改可能是由于使用了执行文件轮换的程序例如 newsyslog 和 logrotate。 这个处理程序在 Unix/Linux 下使用，它会监视文件来查看自上次发出数据后是否有更改。 （如果文件的设备或 inode 发生变化就认为已被更改。） 如果文件被更改，则会关闭旧文件流，并再打开文件以获得新文件流。

这个处理程序不适合在 Windows 下使用，因为在 Windows 下打开的日志文件无法被移动或改名 —— 日志记录会使用排他的锁来打开文件 —— 因此这样的处理程序是没有必要的。 此外，ST_INO 在 Windows 下不受支持；`stat()` 将总是为该值返回零。

class `logging.handlers.``WatchedFileHandler`(filename, mode='a', encoding=None, delay=False, errors=None)

  返回一个 `WatchedFileHandler` 类的新实例。 将打开指定的文件并将其用作日志记录流。 如果未指定 mode，则会使用 `'a'`。 如果 encoding 不为 `None`，则会将其用作打开文件的编码格式。 如果 delay 为真值，则文件打开会被推迟至第一次调用 `emit()` 时。 默认情况下，文件会无限增长。 如果提供了 errors，它会被用于确定编码格式错误的处理方式。

  在 3.6 版更改: 除了字符串值，也接受 `Path` 对象作为 filename 参数。

  在 3.9 版更改: 增加了 errors 形参。

  `reopenIfNeeded`()

    检查文件是否已更改。 如果已更改，则会刷新并关闭现有流然后重新打开文件，这通常是将记录输出到文件的先导操作。

    3.6 新版功能.

  `emit`(record)

    将记录输出到文件，但如果文件已更改则会先调用 `reopenIfNeeded()` 来重新打开它。

## BaseRotatingHandler

`BaseRotatingHandler` 类位于 `logging.handlers` 模块中，它是轮换文件处理程序类 `RotatingFileHandler` 和 `TimedRotatingFileHandler` 的基类。 你不需要实例化此类，但它具有你可能需要重载的属性和方法。

class `logging.handlers.``BaseRotatingHandler`(filename, mode, encoding=None, delay=False, errors=None)

  类的形参与 `FileHandler` 的相同。 其属性有:

  `namer`

    如果此属性被设为一个可调用对象，则 `rotation_filename()` 方法会委托给该可调用对象。 传给该可调用对象的形参与传给 `rotation_filename()` 的相同。

    注解

    namer 函数会在轮换期间被多次调用，因此它应当尽可能的简单快速。 它还应当对给定的输入每次都返回相同的输出，否则轮换行为可能无法按预期工作。

    3.3 新版功能.

  `rotator`

    如果此属性被设为一个可调用对象，则 `rotate()` 方法会委托给该可调用对象。 传给该可调用对象的形参与传给 `rotate()` 的相同。

    3.3 新版功能.

  `rotation_filename`(default_name)

    当轮换时修改日志文件的文件名。

    提供该属性以便可以提供自定义文件名。

    默认实现会调用处理程序的 'namer' 属性，如果它是可调用对象的话，并传给它默认的名称。 如果该属性不是可调用对象 (默认值为 `None`)，则将名称原样返回。

    参数

      default_name -- 日志文件的默认名称。

    3.3 新版功能.

  `rotate`(source, dest)

    当执行轮换时，轮换当前日志。

    默认实现会调用处理程序的 'rotator' 属性，如果它是可调用对象的话，并传给它 source 和 dest 参数。 如果该属性不是可调用对象 (默认值为 `None`)，则将源简单地重命名为目标。

    参数

      - source -- 源文件名。 这通常为基本文件名，例如 'test.log'。

      - dest -- 目标文件名。 这通常是源被轮换后的名称，例如 'test.log.1'。

    3.3 新版功能.

该属性存在的理由是让你不必进行子类化 —— 你可以使用与 `RotatingFileHandler` 和 `TimedRotatingFileHandler` 的实例相同的可调用对象。 如果 namer 或 rotator 可调用对象引发了异常，将会按照与 `emit()` 调用期间的任何其他异常相同的方式来处理，例如通过处理程序的 `handleError()` 方法。

如果你需要对轮换进程执行更多的修改，你可以重载这些方法。

请参阅 Using a rotator and namer to customize log rotation processing 获取具体示例。

## RotatingFileHandler

`RotatingFileHandler` 类位于 `logging.handlers` 模块，它支持磁盘日志文件的轮换。

class `logging.handlers.``RotatingFileHandler`(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False, errors=None)

  返回一个 `RotatingFileHandler` 类的新实例。 将打开指定的文件并将其用作日志记录流。 如果未指定 mode，则会使用 `'a'`。 如果 encoding 不为 `None`，则会将其用作打开文件的编码格式。 如果 delay 为真值，则文件打开会被推迟至第一次调用 `emit()`。 默认情况下，文件会无限增长。 如果提供了 errors，它会被用于确定编码格式错误的处理方式。

  你可以使用 maxBytes 和 backupCount 值来允许文件以预定的大小执行 rollover。 当即将超出预定大小时，将关闭旧文件并打开一个新文件用于输出。 只要当前日志文件长度接近 maxBytes 就会发生轮换；但是如果 maxBytes 或 backupCount 两者之一的值为零，就不会发生轮换，因此你通常要设置 backupCount 至少为 1，而 maxBytes 不能为零。 当 backupCount 为非零值时，系统将通过为原文件名添加扩展名 '.1', '.2' 等来保存旧日志文件。 例如，当 backupCount 为 5 而基本文件名为 `app.log` 时，你将得到 `app.log`, `app.log.1`, `app.log.2` 直至 `app.log.5`。 当前被写入的文件总是 `app.log`。 当此文件写满时，它会被关闭并重户名为 `app.log.1`，而如果文件 `app.log.1`, `app.log.2` 等存在，则它们会被分别重命名为 `app.log.2`, `app.log.3` 等等。

  在 3.6 版更改: 除了字符串值，也接受 `Path` 对象作为 filename 参数。

  在 3.9 版更改: 增加了 errors 形参。

  `doRollover`()

    执行上文所描述的轮换。

  `emit`(record)

    将记录输出到文件，以适应上文所描述的轮换。

## TimedRotatingFileHandler

`TimedRotatingFileHandler` 类位于 `logging.handlers` 模块，它支持基于特定时间间隔的磁盘日志文件轮换。

class `logging.handlers.``TimedRotatingFileHandler`(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False, atTime=None, errors=None)

  返回一个新的 `TimedRotatingFileHandler` 类实例。 指定的文件会被打开并用作日志记录的流。 对于轮换操作它还会设置文件名前缀。 轮换的发生是基于 when 和 interval 的积。

  你可以使用 when 来指定 interval 的类型。 可能的值列表如下。 请注意它们不是大小写敏感的。

  值 | 间隔类型 | 如果/如何使用 atTime
  --- | --- | ---
  `'S'` | 秒 | 忽略
  `'M'` | 分钟 | 忽略
  `'H'` | 小时 | 忽略
  `'D'` | 天 | 忽略
  `'W0'-'W6'` | 工作日(0=星期一) | 用于计算初始轮换时间
  `'midnight'` | 如果未指定 atTime 则在午夜执行轮换，否则将使用 atTime。 | 用于计算初始轮换时间

  当使用基于星期的轮换时，星期一为 'W0'，星期二为 'W1'，以此类推直至星期日为 'W6'。 在这种情况下，传入的 interval 值不会被使用。

  系统将通过为文件名添加扩展名来保存旧日志文件。 扩展名是基于日期和时间的，根据轮换间隔的长短使用 strftime 格式 `%Y-%m-%d_%H-%M-%S` 或是其中有变动的部分。

  当首次计算下次轮换的时间时（即当处理程序被创建时），现有日志文件的上次被修改时间或者当前时间会被用来计算下次轮换的发生时间。

  如果 utc 参数为真值，将使用 UTC 时间；否则会使用本地时间。

  如果 backupCount 不为零，则最多将保留 backupCount 个文件，而如果当轮换发生时创建了更多的文件，则最旧的文件会被删除。 删除逻辑使用间隔时间来确定要删除的文件，因此改变间隔时间可能导致旧文件被继续保留。

  如果 delay 为真值，则会将文件打开延迟到首次调用 `emit()` 的时候。

  如果 atTime 不为 `None`，则它必须是一个 `datetime.time` 的实例，该实例指定轮换在一天内的发生时间，用于轮换被设为“在午夜”或“在每星期的某一天”之类的情况。 请注意在这些情况下，atTime 值实际上会被用于计算 初始 轮换，而后续轮换将会通过正常的间隔时间计算来得出。

  如果指定了 errors，它会被用来确定编码错误的处理方式。

  注解

  初始轮换时间的计算是在处理程序被初始化时执行的。 后续轮换时间的计算则仅在轮换发生时执行，而只有当提交输出时轮换才会发生。 如果不记住这一点，你就可能会感到困惑。 例如，如果设置时间间隔为“每分钟”，那并不意味着你总会看到（文件名中）带有间隔一分钟时间的日志文件；如果在应用程序执行期间，日志记录输出的生成频率高于每分钟一次，那么 你可以预期看到间隔一分钟时间的日志文件。 另一方面，如果（假设）日志记录消息每五分钟才输出一次，那么文件时间将会存在对应于没有输出（因而没有轮换）的缺失。

  在 3.4 版更改: 添加了 atTime 形参。

  在 3.6 版更改: 除了字符串值，也接受 `Path` 对象作为 filename 参数。

  在 3.9 版更改: 增加了 errors 形参。

  `doRollover`()

    执行上文所描述的轮换。

  `emit`(record)

    将记录输出到文件，以适应上文所描述的轮换。

## SocketHandler

`SocketHandler` 类位于 `logging.handlers` 模块，它会将日志记录输出发送到网络套接字。 基类所使用的是 TCP 套接字。

class `logging.handlers.``SocketHandler`(host, port)

  返回一个 `SocketHandler` 类的新实例，该实例旨在与使用 host 与 port 给定地址的远程主机进行通信。

  在 3.4 版更改: 如果 `port` 指定为 `None`，会使用 `host` 中的值来创建一个 Unix 域套接字 —— 在其他情况下，则会创建一个 TCP 套接字。

  `close`()

    关闭套接字。

  `emit`()

    对记录的属性字典执行封存并以二进制格式将其写入套接字。 如果套接字存在错误，则静默地丢弃数据包。 如果连接在此之前丢失，则重新建立连接。 要在接收端将记录解封并输出到 `LogRecord`，请使用 `makeLogRecord()` 函数。

  `handleError`()

    处理在 `emit()` 期间发生的错误。 最可能的原因是连接丢失。 关闭套接字以便我们能在下次事件时重新尝试。

  `makeSocket`()

    这是一个工厂方法，它允许子类定义它们想要的套接字的准确类型。 默认实现会创建一个 TCP 套接字 (`socket.SOCK_STREAM`)。

  `makePickle`(record)

    将记录的属性字典封存为带有长度前缀的二进制格式，并将其返回以准备通过套接字进行传输。 此操作在细节上相当于:

        data = pickle.dumps(record_attr_dict, 1)
        datalen = struct.pack('>L', len(data))
        return datalen + data

    请注意封存操作不是绝对安全的。 如果你关心安全问题，你可能会想要重载此方法以实现更安全的机制。 例如，你可以使用 HMAC 对封存对象进行签名然后在接收端验证它们，或者你也可以在接收端禁用全局对象的解封操作。

  `send`(packet)

    将封存后的字节串 packet 发送到套接字。 所发送字节串的格式与 `makePickle()` 文档中的描述一致。

    此函数允许部分发送，这可能会在网络繁忙时发生。

  `createSocket`()

    尝试创建一个套接字；失败时将使用指数化回退算法处理。 在失败初次发生时，处理程序将丢弃它正尝试发送的消息。 当后续消息交由同一实例处理时，它将不会尝试连接直到经过一段时间以后。 默认形参设置为初始延迟一秒，如果在延迟之后连接仍然无法建立，处理程序将每次把延迟翻倍直至达到 30 秒的最大值。

    此行为由下列处理程序属性控制:

    - `retryStart` (初始延迟，默认为 1.0 秒)。

    - `retryFactor` (倍数，默认为 2.0)。

    - `retryMax` (最大延迟，默认为 30.0 秒)。

    这意味着如果远程监听器在处理程序被使用 之后 启动，你可能会丢失消息（因为处理程序在延迟结束之前甚至不会尝试连接，而在延迟期间静默地丢弃消息）。

## DatagramHandler

The `DatagramHandler` class, located in the `logging.handlers` module, inherits from `SocketHandler` to support sending logging messages over UDP sockets.

class `logging.handlers.``DatagramHandler`(host, port)

  Returns a new instance of the `DatagramHandler` class intended to communicate with a remote machine whose address is given by host and port.

  在 3.4 版更改: If `port` is specified as `None`, a Unix domain socket is created using the value in `host` - otherwise, a UDP socket is created.

  `emit`()

    Pickles the record's attribute dictionary and writes it to the socket in binary format. If there is an error with the socket, silently drops the packet. To unpickle the record at the receiving end into a `LogRecord`, use the `makeLogRecord()` function.

  `makeSocket`()

    The factory method of `SocketHandler` is here overridden to create a UDP socket (`socket.SOCK_DGRAM`).

  `send`(s)

    Send a pickled byte-string to a socket. The format of the sent byte-string is as described in the documentation for `SocketHandler.makePickle()`.

## SysLogHandler

The `SysLogHandler` class, located in the `logging.handlers` module, supports sending logging messages to a remote or local Unix syslog.

class `logging.handlers.``SysLogHandler`(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)

  Returns a new instance of the `SysLogHandler` class intended to communicate with a remote Unix machine whose address is given by address in the form of a `(host, port)` tuple. If address is not specified, `('localhost', 514)` is used. The address is used to open a socket. An alternative to providing a `(host, port)` tuple is providing an address as a string, for example '/dev/log'. In this case, a Unix domain socket is used to send the message to the syslog. If facility is not specified, `LOG_USER` is used. The type of socket opened depends on the socktype argument, which defaults to `socket.SOCK_DGRAM` and thus opens a UDP socket. To open a TCP socket (for use with the newer syslog daemons such as rsyslog), specify a value of `socket.SOCK_STREAM`.

  Note that if your server is not listening on UDP port 514, `SysLogHandler` may appear not to work. In that case, check what address you should be using for a domain socket - it's system dependent. For example, on Linux it's usually '/dev/log' but on OS/X it's '/var/run/syslog'. You'll need to check your platform and use the appropriate address (you may need to do this check at runtime if your application needs to run on several platforms). On Windows, you pretty much have to use the UDP option.

  在 3.2 版更改: socktype was added.

  `close`()

    Closes the socket to the remote host.

  `emit`(record)

    The record is formatted, and then sent to the syslog server. If exception information is present, it is not sent to the server.

    在 3.2.1 版更改: (See: bpo-12168.) In earlier versions, the message sent to the syslog daemons was always terminated with a NUL byte, because early versions of these daemons expected a NUL terminated message - even though it's not in the relevant specification (RFC 5424). More recent versions of these daemons don't expect the NUL byte but strip it off if it's there, and even more recent daemons (which adhere more closely to RFC 5424) pass the NUL byte on as part of the message.

    To enable easier handling of syslog messages in the face of all these differing daemon behaviours, the appending of the NUL byte has been made configurable, through the use of a class-level attribute, `append_nul`. This defaults to `True` (preserving the existing behaviour) but can be set to `False` on a `SysLogHandler` instance in order for that instance to not append the NUL terminator.

    在 3.3 版更改: (See: bpo-12419.) In earlier versions, there was no facility for an "ident" or "tag" prefix to identify the source of the message. This can now be specified using a class-level attribute, defaulting to `""` to preserve existing behaviour, but which can be overridden on a `SysLogHandler` instance in order for that instance to prepend the ident to every message handled. Note that the provided ident must be text, not bytes, and is prepended to the message exactly as is.

  `encodePriority`(facility, priority)

    Encodes the facility and priority into an integer. You can pass in strings or integers - if strings are passed, internal mapping dictionaries are used to convert them to integers.

    The symbolic `LOG_` values are defined in `SysLogHandler` and mirror the values defined in the `sys/syslog.h` header file.

    优先级

    名称（字符串） | 符号值
    --- | ---
    `alert` | LOG_ALERT
    `crit` 或 `critical` | LOG_CRIT
    `debug` | LOG_DEBUG
    `emerg` 或 `panic` | LOG_EMERG
    `err` 或 `error` | LOG_ERR
    `info` | LOG_INFO
    `notice` | LOG_NOTICE
    `warn` 或 `warning` | LOG_WARNING

    设备

    名称（字符串） | 符号值
    --- | ---
    `auth` | LOG_AUTH
    `authpriv` | LOG_AUTHPRIV
    `cron` | LOG_CRON
    `daemon` | LOG_DAEMON
    `ftp` | LOG_FTP
    `kern` | LOG_KERN
    `lpr` | LOG_LPR
    `mail` | LOG_MAIL
    `news` | LOG_NEWS
    `syslog` | LOG_SYSLOG
    `user` | LOG_USER
    `uucp` | LOG_UUCP
    `local0` | LOG_LOCAL0
    `local1` | LOG_LOCAL1
    `local2` | LOG_LOCAL2
    `local3` | LOG_LOCAL3
    `local4` | LOG_LOCAL4
    `local5` | LOG_LOCAL5
    `local6` | LOG_LOCAL6
    `local7` | LOG_LOCAL7

  `mapPriority`(levelname)

    Maps a logging level name to a syslog priority name. You may need to override this if you are using custom levels, or if the default algorithm is not suitable for your needs. The default algorithm maps `DEBUG`, `INFO`, `WARNING`, `ERROR` and `CRITICAL` to the equivalent syslog names, and all other level names to 'warning'.

## NTEventLogHandler

The `NTEventLogHandler` class, located in the `logging.handlers` module, supports sending logging messages to a local Windows NT, Windows 2000 or Windows XP event log. Before you can use it, you need Mark Hammond's Win32 extensions for Python installed.

class `logging.handlers.``NTEventLogHandler`(appname, dllname=None, logtype='Application')

  Returns a new instance of the `NTEventLogHandler` class. The appname is used to define the application name as it appears in the event log. An appropriate registry entry is created using this name. The dllname should give the fully qualified pathname of a .dll or .exe which contains message definitions to hold in the log (if not specified, `'win32service.pyd'` is used - this is installed with the Win32 extensions and contains some basic placeholder message definitions. Note that use of these placeholders will make your event logs big, as the entire message source is held in the log. If you want slimmer logs, you have to pass in the name of your own .dll or .exe which contains the message definitions you want to use in the event log). The logtype is one of `'Application'`, `'System'` or `'Security'`, and defaults to `'Application'`.

  `close`()

    At this point, you can remove the application name from the registry as a source of event log entries. However, if you do this, you will not be able to see the events as you intended in the Event Log Viewer - it needs to be able to access the registry to get the .dll name. The current version does not do this.

  `emit`(record)

    Determines the message ID, event category and event type, and then logs the message in the NT event log.

  `getEventCategory`(record)

    Returns the event category for the record. Override this if you want to specify your own categories. This version returns 0.

  `getEventType`(record)

    Returns the event type for the record. Override this if you want to specify your own types. This version does a mapping using the handler's typemap attribute, which is set up in `__init__()` to a dictionary which contains mappings for `DEBUG`, `INFO`, `WARNING`, `ERROR` and `CRITICAL`. If you are using your own levels, you will either need to override this method or place a suitable dictionary in the handler's typemap attribute.

  `getMessageID`(record)

    Returns the message ID for the record. If you are using your own messages, you could do this by having the msg passed to the logger being an ID rather than a format string. Then, in here, you could use a dictionary lookup to get the message ID. This version returns 1, which is the base message ID in `win32service.pyd`.

## SMTPHandler

The `SMTPHandler` class, located in the `logging.handlers` module, supports sending logging messages to an email address via SMTP.

class `logging.handlers.``SMTPHandler`(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)

  Returns a new instance of the `SMTPHandler` class. The instance is initialized with the from and to addresses and subject line of the email. The toaddrs should be a list of strings. To specify a non-standard SMTP port, use the (host, port) tuple format for the mailhost argument. If you use a string, the standard SMTP port is used. If your SMTP server requires authentication, you can specify a (username, password) tuple for the credentials argument.

  To specify the use of a secure protocol (TLS), pass in a tuple to the secure argument. This will only be used when authentication credentials are supplied. The tuple should be either an empty tuple, or a single-value tuple with the name of a keyfile, or a 2-value tuple with the names of the keyfile and certificate file. (This tuple is passed to the `smtplib.SMTP.starttls()` method.)

  A timeout can be specified for communication with the SMTP server using the timeout argument.

  3.3 新版功能: The timeout argument was added.

  `emit`(record)

    Formats the record and sends it to the specified addressees.

  `getSubject`(record)

    If you want to specify a subject line which is record-dependent, override this method.

## MemoryHandler

The `MemoryHandler` class, located in the `logging.handlers` module, supports buffering of logging records in memory, periodically flushing them to a target handler. Flushing occurs whenever the buffer is full, or when an event of a certain severity or greater is seen.

`MemoryHandler` is a subclass of the more general `BufferingHandler`, which is an abstract class. This buffers logging records in memory. Whenever each record is added to the buffer, a check is made by calling `shouldFlush()` to see if the buffer should be flushed. If it should, then `flush()` is expected to do the flushing.

class `logging.handlers.``BufferingHandler`(capacity)

  Initializes the handler with a buffer of the specified capacity. Here, capacity means the number of logging records buffered.

  `emit`(record)

    Append the record to the buffer. If `shouldFlush()` returns true, call `flush()` to process the buffer.

  `flush`()

    You can override this to implement custom flushing behavior. This version just zaps the buffer to empty.

  `shouldFlush`(record)

    Return `True` if the buffer is up to capacity. This method can be overridden to implement custom flushing strategies.

class `logging.handlers.``MemoryHandler`(capacity, flushLevel=ERROR, target=None, flushOnClose=True)

  Returns a new instance of the `MemoryHandler` class. The instance is initialized with a buffer size of capacity (number of records buffered). If flushLevel is not specified, `ERROR` is used. If no target is specified, the target will need to be set using `setTarget()` before this handler does anything useful. If flushOnClose is specified as `False`, then the buffer is not flushed when the handler is closed. If not specified or specified as `True`, the previous behaviour of flushing the buffer will occur when the handler is closed.

  在 3.6 版更改: The flushOnClose parameter was added.

  `close`()

    Calls `flush()`, sets the target to `None` and clears the buffer.

  `flush`()

    For a `MemoryHandler`, flushing means just sending the buffered records to the target, if there is one. The buffer is also cleared when this happens. Override if you want different behavior.

  `setTarget`(target)

    Sets the target handler for this handler.

  `shouldFlush`(record)

    Checks for buffer full or a record at the flushLevel or higher.

## HTTPHandler

The `HTTPHandler` class, located in the `logging.handlers` module, supports sending logging messages to a Web server, using either `GET` or `POST` semantics.

class `logging.handlers.``HTTPHandler`(host, url, method='GET', secure=False, credentials=None, context=None)

  Returns a new instance of the `HTTPHandler` class. The host can be of the form `host:port`, should you need to use a specific port number. If no method is specified, `GET` is used. If secure is true, a HTTPS connection will be used. The context parameter may be set to a `ssl.SSLContext` instance to configure the SSL settings used for the HTTPS connection. If credentials is specified, it should be a 2-tuple consisting of userid and password, which will be placed in a HTTP 'Authorization' header using Basic authentication. If you specify credentials, you should also specify secure=True so that your userid and password are not passed in cleartext across the wire.

  在 3.5 版更改: The context parameter was added.

  `mapLogRecord`(record)

    Provides a dictionary, based on `record`, which is to be URL-encoded and sent to the web server. The default implementation just returns `record.__dict__`. This method can be overridden if e.g. only a subset of `LogRecord` is to be sent to the web server, or if more specific customization of what's sent to the server is required.

  `emit`(record)

    Sends the record to the Web server as a URL-encoded dictionary. The `mapLogRecord()` method is used to convert the record to the dictionary to be sent.

  注解

  Since preparing a record for sending it to a Web server is not the same as a generic formatting operation, using `setFormatter()` to specify a `Formatter` for a `HTTPHandler` has no effect. Instead of calling `format()`, this handler calls `mapLogRecord()` and then `urllib.parse.urlencode()` to encode the dictionary in a form suitable for sending to a Web server.

## QueueHandler

3.2 新版功能.

The `QueueHandler` class, located in the `logging.handlers` module, supports sending logging messages to a queue, such as those implemented in the `queue` or `multiprocessing` modules.

Along with the `QueueListener` class, `QueueHandler` can be used to let handlers do their work on a separate thread from the one which does the logging. This is important in Web applications and also other service applications where threads servicing clients need to respond as quickly as possible, while any potentially slow operations (such as sending an email via `SMTPHandler`) are done on a separate thread.

class `logging.handlers.``QueueHandler`(queue)

  Returns a new instance of the `QueueHandler` class. The instance is initialized with the queue to send messages to. The queue can be any queue-like object; it's used as-is by the `enqueue()` method, which needs to know how to send messages to it. The queue is not required to have the task tracking API, which means that you can use `SimpleQueue` instances for queue.

  `emit`(record)

    Enqueues the result of preparing the LogRecord. Should an exception occur (e.g. because a bounded queue has filled up), the `handleError()` method is called to handle the error. This can result in the record silently being dropped (if `logging.raiseExceptions` is `False`) or a message printed to `sys.stderr` (if `logging.raiseExceptions` is `True`).

  `prepare`(record)

    Prepares a record for queuing. The object returned by this method is enqueued.

    The base implementation formats the record to merge the message, arguments, and exception information, if present. It also removes unpickleable items from the record in-place.

    You might want to override this method if you want to convert the record to a dict or JSON string, or send a modified copy of the record while leaving the original intact.

  `enqueue`(record)

    Enqueues the record on the queue using `put_nowait()`; you may want to override this if you want to use blocking behaviour, or a timeout, or a customized queue implementation.

## QueueListener

3.2 新版功能.

The `QueueListener` class, located in the `logging.handlers` module, supports receiving logging messages from a queue, such as those implemented in the `queue` or `multiprocessing` modules. The messages are received from a queue in an internal thread and passed, on the same thread, to one or more handlers for processing. While `QueueListener` is not itself a handler, it is documented here because it works hand-in-hand with `QueueHandler`.

Along with the `QueueHandler` class, `QueueListener` can be used to let handlers do their work on a separate thread from the one which does the logging. This is important in Web applications and also other service applications where threads servicing clients need to respond as quickly as possible, while any potentially slow operations (such as sending an email via `SMTPHandler`) are done on a separate thread.

class `logging.handlers.``QueueListener`(queue, *handlers, respect_handler_level=False)

  Returns a new instance of the `QueueListener` class. The instance is initialized with the queue to send messages to and a list of handlers which will handle entries placed on the queue. The queue can be any queue-like object; it's passed as-is to the `dequeue()` method, which needs to know how to get messages from it. The queue is not required to have the task tracking API (though it's used if available), which means that you can use `SimpleQueue` instances for queue.

  If `respect_handler_level` is `True`, a handler's level is respected (compared with the level for the message) when deciding whether to pass messages to that handler; otherwise, the behaviour is as in previous Python versions - to always pass each message to each handler.

  在 3.5 版更改: The `respect_handler_level` argument was added.

  `dequeue`(block)

    Dequeues a record and return it, optionally blocking.

    The base implementation uses `get()`. You may want to override this method if you want to use timeouts or work with custom queue implementations.

  `prepare`(record)

    Prepare a record for handling.

    This implementation just returns the passed-in record. You may want to override this method if you need to do any custom marshalling or manipulation of the record before passing it to the handlers.

  `handle`(record)

    Handle a record.

    This just loops through the handlers offering them the record to handle. The actual object passed to the handlers is that which is returned from `prepare()`.

  `start`()

    Starts the listener.

    This starts up a background thread to monitor the queue for LogRecords to process.

  `stop`()

    Stops the listener.

    This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed.

  `enqueue_sentinel`()

    Writes a sentinel to the queue to tell the listener to quit. This implementation uses `put_nowait()`. You may want to override this method if you want to use timeouts or work with custom queue implementations.

    3.3 新版功能.

参见

模块 `logging`

  日志记录模块的 API 参考。

模块 `logging.config`

  日志记录模块的配置 API 。