Python Glossary Русский

all Python 3loggingterm

logging.FileHandler

handlers

A handler that writes log records to a file. It supports the modes 'a' (append) and 'w' (overwrite), as well as an encoding.

Syntax

handler = logging.FileHandler(filename, mode='a', encoding=None, delay=False)

Before Python 3.15, without encoding='utf-8' the file uses the locale encoding (cp1251 on a Russian Windows): the log turns into mojibake elsewhere, and any character outside that encoding never gets written — logging reports the failure on stderr and drops the line. Mode 'w' truncates the log on every run, so keep the default 'a' when you want history. The file is opened as soon as the handler is built (unless delay=True) and grows without limit — use RotatingFileHandler or TimedRotatingFileHandler from logging.handlers for that.

Examples

import logging
logger = logging.getLogger('myapp')
fh = logging.FileHandler('app.log', mode='a', encoding='utf-8')
fh.setFormatter(logging.Formatter('%(asctime)s %(message)s'))
logger.addHandler(fh)
logger.warning('Записано в файл')

See also

Open in the full glossarydocs.python.orgReport an inaccuracy