Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

logging.Handler.setFormatter — setting a handler's formatter

`logging.Handler.setFormatter` assigns a formatter to a handler or clears it with `None`. It controls output presentation, not the logging level threshold.

Version: Python 3.14; repository image, production runtime not attested

Syntax

handler.setFormatter(fmt)

logging.Handler.setFormatter(fmt) sets the formatter for a particular handler. The method does not check whether fmt is a logging.Formatter instance. The standard implementation of Handler.format(record) can also use another object if it is truthy and provides a compatible format(record) method. A bare format string is not a valid substitute for a formatter. For example, use handler.setFormatter(logging.Formatter("%(levelname)s | %(message)s")).

Calling handler.setFormatter(None) removes the assigned formatter. When the handler uses Handler.format(record), the module's default formatter is then used: an ordinary message receives no level or logger-name prefix. This does not disable logging.

A formatter controls record presentation; level thresholds and filters determine record processing. The setting applies to this handler, not all handlers on the logger. The formatter's output pattern is separate from message-argument interpolation such as logger.info("Items: %s", 3).

The example captures output in io.StringIO, first with a custom format and then after removing it. It omits timestamps and root-logger configuration to keep the result deterministic.

Examples

import io
import logging

stream = io.StringIO()
handler = logging.StreamHandler(stream)
logger = logging.getLogger("demo")
logger.setLevel(logging.INFO)
logger.propagate = False
logger.addHandler(handler)

handler.setFormatter(logging.Formatter("%(levelname)s | %(message)s"))
logger.info("Items: %s", 3)

handler.setFormatter(None)
logger.info("Items: %s", 3)

print(stream.getvalue(), end="")
logger.removeHandler(handler)
handler.close()

Result

INFO | Items: 3
Items: 3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources