Python Glossary Русский

all Python 3loggingterm

logging.StreamHandler

handlers

A handler that writes log records to a stream — sys.stderr by default. Most often used for console output.

Syntax

handler = logging.StreamHandler(stream=None)  # None → sys.stderr

A handler on its own prints nothing until you attach it with logger.addHandler(). A classic slip: basicConfig() has already put a StreamHandler on the root logger, so your own handler makes every message appear twice — once from your handler and once after propagation to root (set logger.propagate = False, or drop the extra handler). The handler level is only a second filter: a record rejected by logger.setLevel() never reaches handler.setLevel() at all.

Examples

import logging, sys
logger = logging.getLogger('app')
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.INFO)
sh.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logger.addHandler(sh)
logger.info('Вывод в stdout')

See also

Open in the full glossarydocs.python.orgReport an inaccuracy