Документация Python неофициальный перевод

logging.config.md

416 строк · 42.5 КБ · обычная страница · сырой текст · скачать

1> **Источник:** https://python-all.ru/3.2/library/logging.config.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# 15.8. [`logging.config`](https://python-all.ru/3.2/library/logging.config.html#module-logging.config) – Конфигурация логирования89Важно1011На этой странице представлена только справочная информация. Учебные руководства см. в1213- [*Базовое руководство*](https://python-all.ru/3.2/howto/logging.html#logging-basic-tutorial)14- [*Продвинутое руководство*](https://python-all.ru/3.2/howto/logging.html#logging-advanced-tutorial)15- [*Поваренная книга по логированию*](https://python-all.ru/3.2/howto/logging-cookbook.html#logging-cookbook)1617В этом разделе описывается API для настройки модуля logging.1819## 15.8.1. Функции конфигурации2021Следующие функции настраивают модуль журналирования. Они находятся в модуле [`logging.config`](https://python-all.ru/3.2/library/logging.config.html#module-logging.config). Их использование необязательно – можно настроить модуль журналирования с помощью этих функций или напрямую обращаясь к основному API (определённому в самом [`logging`](https://python-all.ru/3.2/library/logging.html#module-logging)) и определяя обработчики, которые объявляются либо в [`logging`](https://python-all.ru/3.2/library/logging.html#module-logging), либо в [`logging.handlers`](https://python-all.ru/3.2/library/logging.handlers.html#module-logging.handlers).2223#### `logging.config.dictConfig(config)`2425> Принимает конфигурацию логирования из словаря. Содержимое этого словаря описано ниже в разделе [*Схема словаря конфигурации*](https://python-all.ru/3.2/library/logging.config.html#logging-config-dictschema).26>27> Если во время настройки возникает ошибка, эта функция возбуждает [`ValueError`](https://python-all.ru/3.2/library/exceptions.html#ValueError), [`TypeError`](https://python-all.ru/3.2/library/exceptions.html#TypeError), [`AttributeError`](https://python-all.ru/3.2/library/exceptions.html#AttributeError) или [`ImportError`](https://python-all.ru/3.2/library/exceptions.html#ImportError) с соответствующим описательным сообщением. Ниже приведён (возможно, неполный) список условий, при которых возникнет ошибка:28>29> - Значение `level`, которое не является строкой или является строкой, не соответствующей реальному уровню журналирования.30> - Значение `propagate`, которое не является булевым.31> - Идентификатор, для которого нет соответствующего получателя.32> - Идентификатор несуществующего обработчика, обнаруженный во время инкрементального вызова.33> - Некорректное имя логгера.34> - Невозможность разрешить ссылку на внутренний или внешний объект.35>36> Разбор выполняется классом `DictConfigurator`, конструктору которого передаётся словарь, используемый для настройки, и который имеет метод `configure()`. Модуль [`logging.config`](https://python-all.ru/3.2/library/logging.config.html#module-logging.config) имеет вызываемый атрибут `dictConfigClass`, изначально установленный в `DictConfigurator`. Можно заменить значение `dictConfigClass` на собственную подходящую реализацию.37>38> [`dictConfig()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.dictConfig) вызывает `dictConfigClass`, передавая указанный словарь, а затем вызывает метод `configure()` на возвращённом объекте, чтобы применить настройку:39>40> ```python41> def dictConfig(config):42>     dictConfigClass(config).configure()43> ```44>45> Например, подкласс `DictConfigurator` может вызывать `DictConfigurator.__init__()` в собственном [`__init__()`](https://python-all.ru/3.2/reference/datamodel.html#object.__init__), затем настроить пользовательские префиксы, которые будут использоваться в последующем вызове `configure()`. Атрибут `dictConfigClass` будет привязан к этому новому подклассу, и после этого [`dictConfig()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.dictConfig) можно вызывать точно так же, как в состоянии по умолчанию, без пользовательских настроек.4647Новое в версии 3.2.4849#### `logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)`5051Читает конфигурацию логирования из файла формата [`configparser`](https://python-all.ru/3.2/library/configparser.html#module-configparser) с именем *fname*. Эту функцию можно вызывать несколько раз из приложения, что позволяет конечному пользователю выбирать из различных предопределённых конфигураций (если разработчик предоставит механизм для отображения вариантов и загрузки выбранной конфигурации).5253| Параметры: | **defaults** – значения по умолчанию, передаваемые ConfigParser, можно указать в этом аргументе. **disable\_existing\_loggers** – если указано как `False`, то существующие на момент вызова логгеры остаются без изменений. Значение по умолчанию – `True`, поскольку это обеспечивает обратную совместимость со старым поведением. Такое поведение отключает все существующие логгеры, если они или их предки явно не указаны в конфигурации логирования. |54| --- | --- |5556#### `logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT)`5758Запускает сокет-сервер на указанном порту и ожидает новые конфигурации. Если порт не указан, используется значение по умолчанию модуля `DEFAULT_LOGGING_CONFIG_PORT`. Конфигурации логирования отправляются в виде файла, пригодного для обработки функцией [`fileConfig()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.fileConfig). Возвращает экземпляр `поток`, на котором можно вызвать `start()` для запуска сервера и к которому при необходимости можно применить `join()`. Чтобы остановить сервер, вызовите [`stopListening()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.stopListening).5960Чтобы отправить конфигурацию в сокет, прочитайте файл конфигурации и отправьте его в сокет в виде строки байтов, перед которой идёт четырёхбайтовая длина, упакованная в двоичном виде с помощью `struct.pack('>L', n)`.6162> **Примечание**63>64> Поскольку части конфигурации передаются через [`eval()`](https://python-all.ru/3.2/library/functions.html#eval), использование этой функции может представлять угрозу безопасности. Хотя функция привязывается только к сокету на `localhost` и поэтому не принимает соединения с удаленных машин, существуют сценарии, в которых недоверенный код может быть выполнен от имени процесса, вызывающего [`listen()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.listen). В частности, если процесс, вызывающий [`listen()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.listen), работает на многопользовательской машине, где пользователи не доверяют друг другу, то злоумышленник может организовать выполнение произвольного кода в процессе жертвы, просто подключившись к сокету [`listen()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.listen) жертвы и отправив конфигурацию, которая запускает любой код, который злоумышленник хочет выполнить в процессе жертвы. Это особенно легко сделать, если используется порт по умолчанию, но не сложно, даже если используется другой порт).6566#### `logging.config.stopListening()`6768Останавливает сервер прослушивания, созданный вызовом [`listen()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.listen). Обычно вызывается перед вызовом `join()` на возвращаемом значении [`listen()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.listen).6970## 15.8.2. Схема словаря конфигурации7172Описание конфигурации журналирования требует перечисления различных создаваемых объектов и связей между ними; например, можно создать обработчик с именем 'console', а затем указать, что регистратор с именем 'startup' будет отправлять свои сообщения обработчику 'console'. Эти объекты не ограничиваются теми, что предоставляет модуль [`logging`](https://python-all.ru/3.2/library/logging.html#module-logging), поскольку можно написать собственный класс форматировщика или обработчика. Параметры этих классов также могут включать внешние объекты, такие как `sys.stderr`. Синтаксис описания этих объектов и связей определён в разделе [*Связи объектов*](https://python-all.ru/3.2/library/logging.config.html#logging-config-dict-connections) ниже.7374### 15.8.2.1. Подробности схемы словаря7576Словарь, передаваемый в [`dictConfig()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.dictConfig), должен содержать следующие ключи:7778- *version* – должно быть установлено целочисленное значение, представляющее версию схемы. Единственное допустимое значение на данный момент – 1, но наличие этого ключа позволяет схеме развиваться, сохраняя обратную совместимость.7980Все остальные ключи необязательны, но если они присутствуют, то будут интерпретироваться, как описано ниже. Во всех случаях, когда ниже упоминается «настраивающий словарь», в нём будет проверяться наличие специального ключа `'()'`, чтобы определить, требуется ли пользовательское создание экземпляра. Если да, то используется механизм, описанный ниже в разделе [*Пользовательские объекты*](https://python-all.ru/3.2/library/logging.config.html#logging-config-dict-userdef), для создания экземпляра; в противном случае контекст используется для определения того, что создавать.8182- *formatters* – соответствующим значением будет словарь, в котором каждый ключ – это идентификатор форматтера, а каждое значение – словарь, описывающий, как настроить соответствующий экземпляр Formatter.8384  В словаре конфигурации ищутся ключи `format` и `datefmt` (со значениями по умолчанию `None`), которые используются для создания экземпляра [`logging.Formatter`](https://python-all.ru/3.2/library/logging.html#logging.Formatter).85- *filters* – соответствующее значение будет словарём, в котором каждый ключ – это идентификатор фильтра, а каждое значение – словарь, описывающий, как настроить соответствующий экземпляр Filter.8687  В настроечном словаре ищется ключ `name` (по умолчанию пустая строка), и он используется для создания экземпляра [`logging.Filter`](https://python-all.ru/3.2/library/logging.html#logging.Filter).88- *handlers* – соответствующее значение будет словарём, в котором каждый ключ – это идентификатор обработчика, а каждое значение – словарь, описывающий, как настроить соответствующий экземпляр Handler.8990  В словаре конфигурации ищутся следующие ключи:9192  - `class` (обязательно). Это полностью определённое имя класса обработчика.93  - `level` (необязательно). Уровень обработчика.94  - `formatter` (необязательно). Идентификатор форматировщика для этого обработчика.95  - `filters` (optional). A list of ids of the filters for this handler.9697  Все *остальные* ключи передаются как именованные аргументы конструктору обработчика. Например, для следующего фрагмента:9899  ```python100  handlers:101    console:102      class : logging.StreamHandler103      formatter: brief104      level   : INFO105      filters: [allow_foo]106      stream  : ext://sys.stdout107    file:108      class : logging.handlers.RotatingFileHandler109      formatter: precise110      filename: logconfig.log111      maxBytes: 1024112      backupCount: 3113  ```114115  the handler with id `console` is instantiated as a [`logging.StreamHandler`](https://python-all.ru/3.2/library/logging.handlers.html#logging.StreamHandler), using `sys.stdout` as the underlying stream. The handler with id `file` is instantiated as a [`logging.handlers.RotatingFileHandler`](https://python-all.ru/3.2/library/logging.handlers.html#logging.handlers.RotatingFileHandler) with the keyword arguments `filename='logconfig.log', maxBytes=1024, backupCount=3`.116- *loggers* – соответствующее значение будет словарём, в котором каждый ключ – это имя регистратора, а каждое значение – словарь, описывающий, как настроить соответствующий экземпляр Logger.117118  В словаре конфигурации ищутся следующие ключи:119120  - `level` (optional). The level of the logger.121  - `propagate` (optional). The propagation setting of the logger.122  - `filters` (optional). A list of ids of the filters for this logger.123  - `handlers` (optional). A list of ids of the handlers for this logger.124125  Указанные регистраторы будут настроены в соответствии с заданными уровнем, распространением, фильтрами и обработчиками.126- *root* - this will be the configuration for the root logger. Processing of the configuration will be as for any logger, except that the `propagate` setting will not be applicable.127- *incremental* - whether the configuration is to be interpreted as incremental to the existing configuration. This value defaults to `False`, which means that the specified configuration replaces the existing configuration with the same semantics as used by the existing [`fileConfig()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.fileConfig) API.128129  If the specified value is `True`, the configuration is processed as described in the section on [*Incremental Configuration*](https://python-all.ru/3.2/library/logging.config.html#logging-config-dict-incremental).130- *disable\_existing\_loggers* - whether any existing loggers are to be disabled. This setting mirrors the parameter of the same name in [`fileConfig()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.fileConfig). If absent, this parameter defaults to `True`. This value is ignored if *incremental* is `True`.131132### 15.8.2.2. Инкрементальная конфигурация133134Обеспечить полную гибкость для инкрементальной конфигурации сложно. Например, поскольку такие объекты, как фильтры и форматировщики, анонимны, после настройки невозможно сослаться на эти анонимные объекты при дополнении конфигурации.135136Кроме того, нет убедительных причин произвольно изменять граф объектов регистраторов, обработчиков, фильтров и форматировщиков во время выполнения после настройки: уровень подробности регистрации можно контролировать просто установкой уровней (а для регистраторов – флагов распространения). Произвольное изменение графа объектов безопасным способом проблематично в многопоточной среде; хотя это возможно, выгода не стоит сложности, которую это вносит в реализацию.137138Thus, when the `incremental` key of a configuration dict is present and is `True`, the system will completely ignore any `formatters` and `filters` entries, and process only the `level` settings in the `handlers` entries, and the `level` and `propagate` settings in the `loggers` and `root` entries.139140Использование значения в словаре конфигурации позволяет отправлять конфигурации по сети в виде сериализованных словарей в сокетный слушатель. Таким образом, уровень подробности регистрации долго работающего приложения можно изменять со временем без необходимости останавливать и перезапускать приложение.141142### 15.8.2.3. Связи объектов143144Схема описывает набор объектов логирования – регистраторы, обработчики, форматировщики, фильтры – которые соединены друг с другом в граф объектов. Таким образом, схема должна представлять соединения между объектами. Например, предположим, что после настройки к определённому регистратору прикреплён определённый обработчик. В рамках данного обсуждения можно сказать, что регистратор представляет источник, а обработчик – приёмник соединения между ними. Конечно, в настроенных объектах это реализовано тем, что регистратор хранит ссылку на обработчик. В словаре конфигурации это делается путём присвоения каждому объекту- приёмнику идентификатора, однозначно его определяющего, а затем использования этого идентификатора в конфигурации объекта-источника для указания наличия соединения между источником и объектом-приёмником с этим идентификатором.145146Например, рассмотрим следующий фрагмент YAML:147148```python149formatters:150  brief:151    # здесь задаётся конфигурация форматтера с id 'brief'152  precise:153    # здесь задаётся конфигурация форматтера с id 'precise'154handlers:155  h1: #Это идентификатор156   # здесь задаётся конфигурация обработчика с id 'h1'157   formatter: brief158  h2: #Это другой идентификатор159   # здесь задаётся конфигурация обработчика с id 'h2'160   formatter: precise161loggers:162  foo.bar.baz:163    # прочая конфигурация для логгера 'foo.bar.baz'164    handlers: [h1, h2]165```166167(Примечание: YAML используется здесь, потому что он немного более читаем, чем эквивалентная форма исходного кода Python для словаря.)168169The ids for loggers are the logger names which would be used programmatically to obtain a reference to those loggers, e.g. `foo.bar.baz`. The ids for Formatters and Filters can be any string value (such as `brief`, `precise` above) and they are transient, in that they are only meaningful for processing the configuration dictionary and used to determine connections between objects, and are not persisted anywhere when the configuration call is complete.170171The above snippet indicates that logger named `foo.bar.baz` should have two handlers attached to it, which are described by the handler ids `h1` and `h2`. The formatter for `h1` is that described by id `brief`, and the formatter for `h2` is that described by id `precise`.172173### 15.8.2.4. Пользовательские объекты174175Схема поддерживает пользовательские объекты для обработчиков, фильтров и форматировщиков. (Регистраторам не нужны разные типы для разных экземпляров, поэтому в этой схеме конфигурации нет поддержки пользовательских классов регистраторов.)176177Настраиваемые объекты описываются словарями, которые детализируют их конфигурацию. В некоторых местах система логирования сможет определить из контекста, как создать экземпляр объекта, но когда требуется создать экземпляр пользовательского объекта, система не будет знать, как это сделать. Для обеспечения полной гибкости при создании пользовательских объектов пользователь должен предоставить «фабрику» – вызываемый объект, который вызывается со словарём конфигурации и возвращает созданный экземпляр. Это обозначается абсолютным путём импорта к фабрике, доступным под специальным ключом `'()'`. Вот конкретный пример:178179```python180formatters:181  brief:182    format: '%(message)s'183  default:184    format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'185    datefmt: '%Y-%m-%d %H:%M:%S'186  custom:187      (): my.package.customFormatterFactory188      bar: baz189      spam: 99.9190      answer: 42191```192193The above YAML snippet defines three formatters. The first, with id `brief`, is a standard [`logging.Formatter`](https://python-all.ru/3.2/library/logging.html#logging.Formatter) instance with the specified format string. The second, with id `default`, has a longer format and also defines the time format explicitly, and will result in a [`logging.Formatter`](https://python-all.ru/3.2/library/logging.html#logging.Formatter) initialized with those two format strings. Shown in Python source form, the `brief` and `default` formatters have configuration sub-dictionaries:194195```python196{197  'format' : '%(message)s'198}199```200201и:202203```python204{205  'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',206  'datefmt' : '%Y-%m-%d %H:%M:%S'207}208```209210respectively, and as these dictionaries do not contain the special key `'()'`, the instantiation is inferred from the context: as a result, standard [`logging.Formatter`](https://python-all.ru/3.2/library/logging.html#logging.Formatter) instances are created. The configuration sub-dictionary for the third formatter, with id `custom`, is:211212```python213{214  '()' : 'my.package.customFormatterFactory',215  'bar' : 'baz',216  'spam' : 99.9,217  'answer' : 42218}219```220221and this contains the special key `'()'`, which means that user-defined instantiation is wanted. In this case, the specified factory callable will be used. If it is an actual callable it will be used directly - otherwise, if you specify a string (as in the example) the actual callable will be located using normal import mechanisms. The callable will be called with the **remaining** items in the configuration sub-dictionary as keyword arguments. In the above example, the formatter with id `custom` will be assumed to be returned by the call:222223```python224my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)225```226227Ключ `'()'` был выбран в качестве специального, потому что он не является допустимым именем параметра ключевого слова и, следовательно, не будет конфликтовать с именами именованных аргументов, используемых при вызове. `'()'` также служит мнемоническим напоминанием о том, что соответствующее значение является вызываемым объектом.228229### 15.8.2.5. Доступ к внешним объектам230231There are times where a configuration needs to refer to objects external to the configuration, for example `sys.stderr`. If the configuration dict is constructed using Python code, this is straightforward, but a problem arises when the configuration is provided via a text file (e.g. JSON, YAML). In a text file, there is no standard way to distinguish `sys.stderr` from the literal string `'sys.stderr'`. To facilitate this distinction, the configuration system looks for certain special prefixes in string values and treat them specially. For example, if the literal string `'ext://sys.stderr'` is provided as a value in the configuration, then the `ext://` will be stripped off and the remainder of the value processed using normal import mechanisms.232233The handling of such prefixes is done in a way analogous to protocol handling: there is a generic mechanism to look for prefixes which match the regular expression `^(?P<prefix>[a-z]+)://(?P<suffix>.*)$` whereby, if the `prefix` is recognised, the `suffix` is processed in a prefix-dependent manner and the result of the processing replaces the string value. If the prefix is not recognised, then the string value will be left as-is.234235### 15.8.2.6. Доступ к внутренним объектам236237As well as external objects, there is sometimes also a need to refer to objects in the configuration. This will be done implicitly by the configuration system for things that it knows about. For example, the string value `'DEBUG'` for a `level` in a logger or handler will automatically be converted to the value `logging.DEBUG`, and the `handlers`, `filters` and `formatter` entries will take an object id and resolve to the appropriate destination object.238239However, a more generic mechanism is needed for user-defined objects which are not known to the [`logging`](https://python-all.ru/3.2/library/logging.html#module-logging) module. For example, consider [`logging.handlers.MemoryHandler`](https://python-all.ru/3.2/library/logging.handlers.html#logging.handlers.MemoryHandler), which takes a `target` argument which is another handler to delegate to. Since the system already knows about this class, then in the configuration, the given `target` just needs to be the object id of the relevant target handler, and the system will resolve to the handler from the id. If, however, a user defines a `my.package.MyHandler` which has an `alternate` handler, the configuration system would not know that the `alternate` referred to a handler. To cater for this, a generic resolution system allows the user to specify:240241```python242handlers:243  file:244    # здесь задаётся конфигурация файлового обработчика245246  custom:247    (): my.package.MyHandler248    alternate: cfg://handlers.file249```250251The literal string `'cfg://handlers.file'` will be resolved in an analogous way to strings with the `ext://` prefix, but looking in the configuration itself rather than the import namespace. The mechanism allows access by dot or by index, in a similar way to that provided by `str.format`. Thus, given the following snippet:252253```python254handlers:255  email:256    class: logging.handlers.SMTPHandler257    mailhost: localhost258    fromaddr: my_app@domain.tld259    toaddrs:260      - support_team@domain.tld261      - dev_team@domain.tld262    subject: Houston, we have a problem.263```264265in the configuration, the string `'cfg://handlers'` would resolve to the dict with key `handlers`, the string `'cfg://handlers.email` would resolve to the dict with key `email` in the `handlers` dict, and so on. The string `'cfg://handlers.email.toaddrs[1]` would resolve to `'dev_team.domain.tld'` and the string `'cfg://handlers.email.toaddrs[0]'` would resolve to the value `'support_team@domain.tld'`. The `subject` value could be accessed using either `'cfg://handlers.email.subject'` or, equivalently, `'cfg://handlers.email[subject]'`. The latter form only needs to be used if the key contains spaces or non-alphanumeric characters. If an index value consists only of decimal digits, access will be attempted using the corresponding integer value, falling back to the string value if needed.266267Given a string `cfg://handlers.myhandler.mykey.123`, this will resolve to `config_dict['handlers']['myhandler']['mykey']['123']`. If the string is specified as `cfg://handlers.myhandler.mykey[123]`, the system will attempt to retrieve the value from `config_dict['handlers']['myhandler']['mykey'][123]`, and fall back to `config_dict['handlers']['myhandler']['mykey']['123']` if that fails.268269### 15.8.2.7. Разрешение импорта и пользовательские импортёры270271Import resolution, by default, uses the builtin [`__import__()`](https://python-all.ru/3.2/library/functions.html#__import__) function to do its importing. You may want to replace this with your own importing mechanism: if so, you can replace the `importer` attribute of the `DictConfigurator` or its superclass, the `BaseConfigurator` class. However, you need to be careful because of the way functions are accessed from classes via descriptors. If you are using a Python callable to do your imports, and you want to define it at class level rather than instance level, you need to wrap it with [`staticmethod()`](https://python-all.ru/3.2/library/functions.html#staticmethod). For example:272273```python274from importlib import import_module275from logging.config import BaseConfigurator276277BaseConfigurator.importer = staticmethod(import_module)278```279280You don’t need to wrap with [`staticmethod()`](https://python-all.ru/3.2/library/functions.html#staticmethod) if you’re setting the import callable on a configurator *instance*.281282## 15.8.3. Формат файла конфигурации283284The configuration file format understood by [`fileConfig()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.fileConfig) is based on [`configparser`](https://python-all.ru/3.2/library/configparser.html#module-configparser) functionality. The file must contain sections called `[loggers]`, `[handlers]` and `[formatters]` which identify by name the entities of each type which are defined in the file. For each such entity, there is a separate section which identifies how that entity is configured. Thus, for a logger named `log01` in the `[loggers]` section, the relevant configuration details are held in a section `[logger_log01]`. Similarly, a handler called `hand01` in the `[handlers]` section will have its configuration held in a section called `[handler_hand01]`, while a formatter called `form01` in the `[formatters]` section will have its configuration specified in a section called `[formatter_form01]`. The root logger configuration must be specified in a section called `[logger_root]`.285286Примеры таких разделов в файле приведены ниже.287288```python289[loggers]290keys=root,log02,log03,log04,log05,log06,log07291292[handlers]293keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09294295[formatters]296keys=form01,form02,form03,form04,form05,form06,form07,form08,form09297```298299Корневой регистратор должен указывать уровень и список обработчиков. Пример раздела корневого регистратора приведен ниже.300301```python302[logger_root]303level=NOTSET304handlers=hand01305```306307The `level` entry can be one of `DEBUG, INFO, WARNING, ERROR, CRITICAL` or `NOTSET`. For the root logger only, `NOTSET` means that all messages will be logged. Level values are [`eval()`](https://python-all.ru/3.2/library/functions.html#eval)uated in the context of the `logging` package’s namespace.308309The `handlers` entry is a comma-separated list of handler names, which must appear in the `[handlers]` section. These names must appear in the `[handlers]` section and have corresponding sections in the configuration file.310311Для регистраторов, отличных от корневого, требуется некоторая дополнительная информация. Это проиллюстрировано следующим примером.312313```python314[logger_parser]315level=DEBUG316handlers=hand01317propagate=1318qualname=compiler.parser319```320321The `level` and `handlers` entries are interpreted as for the root logger, except that if a non-root logger’s level is specified as `NOTSET`, the system consults loggers higher up the hierarchy to determine the effective level of the logger. The `propagate` entry is set to 1 to indicate that messages must propagate to handlers higher up the logger hierarchy from this logger, or 0 to indicate that messages are **not** propagated to handlers up the hierarchy. The `qualname` entry is the hierarchical channel name of the logger, that is to say the name used by the application to get the logger.322323Разделы, которые задают конфигурацию обработчика, иллюстрируются следующим примером.324325```python326[handler_hand01]327class=StreamHandler328level=NOTSET329formatter=form01330args=(sys.stdout,)331```332333The `class` entry indicates the handler’s class (as determined by [`eval()`](https://python-all.ru/3.2/library/functions.html#eval) in the `logging` package’s namespace). The `level` is interpreted as for loggers, and `NOTSET` is taken to mean ‘log everything’.334335The `formatter` entry indicates the key name of the formatter for this handler. If blank, a default formatter (`logging._defaultFormatter`) is used. If a name is specified, it must appear in the `[formatters]` section and have a corresponding section in the configuration file.336337Запись `args` при вычислении [`eval()`](https://python-all.ru/3.2/library/functions.html#eval) в контексте пространства имён пакета `logging` представляет собой список аргументов для конструктора класса обработчика. Обратитесь к конструкторам соответствующих обработчиков или к примерам ниже, чтобы узнать, как формируются типичные записи.338339```python340[handler_hand02]341class=FileHandler342level=DEBUG343formatter=form02344args=('python.log', 'w')345346[handler_hand03]347class=handlers.SocketHandler348level=INFO349formatter=form03350args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)351352[handler_hand04]353class=handlers.DatagramHandler354level=WARN355formatter=form04356args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)357358[handler_hand05]359class=handlers.SysLogHandler360level=ERROR361formatter=form05362args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)363364[handler_hand06]365class=handlers.NTEventLogHandler366level=CRITICAL367formatter=form06368args=('Python Application', '', 'Application')369370[handler_hand07]371class=handlers.SMTPHandler372level=WARN373formatter=form07374args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')375376[handler_hand08]377class=handlers.MemoryHandler378level=NOTSET379formatter=form08380target=381args=(10, ERROR)382383[handler_hand09]384class=handlers.HTTPHandler385level=NOTSET386formatter=form09387args=('localhost:9022', '/log', 'GET')388```389390Разделы, которые задают конфигурацию форматировщика, обычно выглядят следующим образом.391392```python393[formatter_form01]394format=F1 %(asctime)s %(levelname)s %(message)s395datefmt=396class=logging.Formatter397```398399Запись `format` задаёт общую строку форматирования, а запись `datefmt` – строку формата даты/времени, совместимую с `strftime()`. Если она пуста, пакет подставляет дату/время в формате ISO8601, что почти эквивалентно указанию строки формата `'%Y-%m-%d %H:%M:%S'`. Формат ISO8601 также включает миллисекунды, которые добавляются к результату использования указанной выше строки форматирования через запятую. Пример времени в формате ISO8601: `2003-01-23 00:29:50,411`.400401Запись `class` необязательна. Она указывает имя класса форматтера (в виде точечного имени модуля и класса). Эта опция полезна для создания экземпляра подкласса `Formatter`. Подклассы `Formatter` могут отображать трассировки исключений в расширенном или сжатом формате.402403> **Примечание**404>405> Из-за использования [`eval()`](https://python-all.ru/3.2/library/functions.html#eval), как описано выше, существуют потенциальные риски безопасности, связанные с использованием [`listen()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.listen) для отправки и получения конфигураций через сокеты. Эти риски ограничены случаями, когда несколько пользователей, не доверяющих друг другу, выполняют код на одной машине; см. документацию по [`listen()`](https://python-all.ru/3.2/library/logging.config.html#logging.config.listen) для получения дополнительной информации.406407> **См. также**408>409> **Модуль [`logging`](https://python-all.ru/3.2/library/logging.html#module-logging)**410>411> Справочник API для модуля logging.412>413> **Модуль [`logging.handlers`](https://python-all.ru/3.2/library/logging.handlers.html#module-logging.handlers)**414>415> Полезные обработчики, входящие в состав модуля logging.416