提交 58dc7ac3 编写于 作者: O ogorbacheva 提交者: Ivan Blinkov

Doc fix: Added `system.query_log` table (#5039)

上级 118bea2b
......@@ -528,18 +528,18 @@ The path to the directory containing data.
```
## query_log
## query_log {#server_settings-query-log}
Setting for logging queries received with the [log_queries=1](../settings/settings.md) setting.
Queries are logged in the ClickHouse table, not in a separate file.
Queries are logged in the [system.query_log](../system_tables.md#system_tables-query-log) table, not in a separate file. You can change the name of the table in the `table` parameter (see below).
Use the following parameters to configure logging:
- database – Name of the database.
- table – Name of the table.
- partition_by – Sets a [custom partitioning key](../../operations/table_engines/custom_partitioning_key.md).
- flush_interval_milliseconds – Interval for flushing data from the buffer in memory to the table.
- `database` – Name of the database.
- `table` – Name of the system table the queries will be logged in.
- `partition_by` – Sets a [custom partitioning key](../../operations/table_engines/custom_partitioning_key.md) for a system table.
- `flush_interval_milliseconds` – Interval for flushing data from the buffer in memory to the table.
If the table doesn't exist, ClickHouse will create it. If the structure of the query log changed when the ClickHouse server was updated, the table with the old structure is renamed, and a new table is created automatically.
......
......@@ -313,11 +313,11 @@ ClickHouse uses this setting when reading data from tables. If the total storage
**Default value**: 0.
## log_queries
## log_queries {#settings-log-queries}
Setting up query logging.
Queries sent to ClickHouse with this setup are logged according to the rules in the [query_log](../server_settings/settings.md) server configuration parameter.
Queries sent to ClickHouse with this setup are logged according to the rules in the [query_log](../server_settings/settings.md#server_settings-query-log) server configuration parameter.
**Example**:
......
......@@ -254,6 +254,96 @@ query String - The query text. For INSERT, it doesn't include the da
query_id String - Query ID, if defined.
```
## system.query_log {#system_tables-query-log}
Contains information about queries execution. For each query, you can see processing start time, duration of processing, error message and other information.
!!! note
The table doesn't contain input data for `INSERT` queries.
ClickHouse creates this table only if the [query_log](server_settings/settings.md#server_settings-query-log) server parameter is specified. This parameter sets the logging rules. For example, a logging interval or name of a table the queries will be logged in.
To enable query logging, set the parameter [log_queries](settings/settings.md#settings-log-queries) to 1. For details, see the [Settings](settings/settings.md) section.
The `system.query_log` table registers two kinds of queries:
1. Initial queries, that were run directly by the client.
2. Child queries that were initiated by other queries (for distributed query execution). For such a kind of queries, information about the parent queries is shown in the `initial_*` columns.
Columns:
- `type` (UInt8) — Type of event that occurred when executing the query. Possible values:
- 1 — Successful start of query execution.
- 2 — Successful end of query execution.
- 3 — Exception before the start of query execution.
- 4 — Exception during the query execution.
- `event_date` (Date) — Event date.
- `event_time` (DateTime) — Event time.
- `query_start_time` (DateTime) — Time of the query processing start.
- `query_duration_ms` (UInt64) — Duration of the query processing.
- `read_rows` (UInt64) — Number of read rows.
- `read_bytes` (UInt64) — Number of read bytes.
- `written_rows` (UInt64) — For `INSERT` queries, number of written rows. For other queries, the column value is 0.
- `written_bytes` (UInt64) — For `INSERT` queries, number of written bytes. For other queries, the column value is 0.
- `result_rows` (UInt64) — Number of rows in a result.
- `result_bytes` (UInt64) — Number of bytes in a result.
- `memory_usage` (UInt64) — Memory consumption by the query.
- `query` (String) — Query string.
- `exception` (String) — Exception message.
- `stack_trace` (String) — Stack trace (a list of methods called before the error occurred). An empty string, if the query is completed successfully.
- `is_initial_query` (UInt8) — Kind of query. Possible values:
- 1 — Query was initiated by the client.
- 0 — Query was initiated by another query for distributed query execution.
- `user` (String) — Name of the user initiated the current query.
- `query_id` (String) — ID of the query.
- `address` (FixedString(16)) — IP address the query was initiated from.
- `port` (UInt16) — A server port that was used to receive the query.
- `initial_user` (String) — Name of the user who run the parent query (for distributed query execution).
- `initial_query_id` (String) — ID of the parent query.
- `initial_address` (FixedString(16)) — IP address that the parent query was launched from.
- `initial_port` (UInt16) — A server port that was used to receive the parent query from the client.
- `interface` (UInt8) — Interface that the query was initiated from. Possible values:
- 1 — TCP.
- 2 — HTTP.
- `os_user` (String) — User's OS.
- `client_hostname` (String) — Server name that the [clickhouse-client](../interfaces/cli.md) is connected to.
- `client_name` (String) — The [clickhouse-client](../interfaces/cli.md) name.
- `client_revision` (UInt32) — Revision of the [clickhouse-client](../interfaces/cli.md).
- `client_version_major` (UInt32) — Major version of the [clickhouse-client](../interfaces/cli.md).
- `client_version_minor` (UInt32) — Minor version of the [clickhouse-client](../interfaces/cli.md).
- `client_version_patch` (UInt32) — Patch component of the [clickhouse-client](../interfaces/cli.md) version.
- `http_method` (UInt8) — HTTP method initiated the query. Possible values:
- 0 — The query was launched from the TCP interface.
- 1 — `GET` method is used.
- 2 — `POST` method is used.
- `http_user_agent` (String) — The `UserAgent` header passed in the HTTP request.
- `quota_key` (String) — The quota key specified in [quotas](quotas.md) setting.
- `revision` (UInt32) — ClickHouse revision.
- `thread_numbers` (Array(UInt32)) — Number of threads that are participating in query execution.
- `ProfileEvents.Names` (Array(String)) — Counters that measure the following metrics:
- Time spent on reading and writing over the network.
- Time spent on reading and writing to a disk.
- Number of network errors.
- Time spent on waiting when the network bandwidth is limited.
- `ProfileEvents.Values` (Array(UInt64)) — Values of metrics that are listed in the `ProfileEvents.Names` column.
- `Settings.Names` (Array(String)) — Names of settings that were changed when the client run a query. To enable logging of settings changing, set the `log_query_settings` parameter to 1.
- `Settings.Values` (Array(String)) — Values of settings that are listed in the `Settings.Names` column.
Each query creates one or two rows in the `query_log` table, depending on the status of the query:
1. If the query execution is successful, two events with types 1 and 2 are created (see the `type` column).
2. If the error occurred during the query processing, two events with types 1 and 4 are created.
3. If the error occurred before the query launching, a single event with type 3 is created.
By default, logs are added into the table at intervals of 7,5 seconds. You can set this interval in the [query_log](server_settings/settings.md#server_settings-query-log) server setting (see the `flush_interval_milliseconds` parameter). To flush the logs forcibly from the memory buffer into the table, use the `SYSTEM FLUSH LOGS` query.
When the table is deleted manually, it will be automatically created on the fly. Note that all the previous logs will be deleted.
!!! note
The storage period for logs is unlimited; the logs aren't automatically deleted from the table. You need to organize the removing of non-actual logs yourself.
You can specify an arbitrary partitioning key for the `system.query_log` table in the [query_log](server_settings/settings.md#server_settings-query-log) server setting (see the `partition_by` parameter).
## system.replicas {#system_tables-replicas}
Contains information and status for replicated tables residing on the local server.
......
......@@ -528,18 +528,18 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
```
## query_log
## query_log {#server_settings-query-log}
Настройка логгирования запросов, принятых с настройкой [log_queries=1](../settings/settings.md).
Настройка логирования запросов, принятых с настройкой [log_queries=1](../settings/settings.md).
Запросы логгируются не в отдельный файл, а в таблицу ClickHouse.
Запросы логируются не в отдельный файл, а в системную таблицу [system.query_log](../system_tables.md#system_tables-query-log). Вы можете изменить название этой таблицы в параметре `table` (см. ниже).
При настройке логгирования используются следующие параметры:
При настройке логирования используются следующие параметры:
- database - Имя базы данных.
- table - Имя таблицы.
- partition_by - Устанавливает [произвольный ключ партиционирования](../../operations/table_engines/custom_partitioning_key.md).
- flush_interval_milliseconds - Период сброса данных из буфера в памяти в таблицу.
- `database` — имя базы данных;
- `table` — имя таблицы, куда будет записываться лог;
- `partition_by`[произвольный ключ партиционирования](../../operations/table_engines/custom_partitioning_key.md) для таблицы с логами;
- `flush_interval_milliseconds` — период сброса данных из буфера в памяти в таблицу.
Если таблица не существует, то ClickHouse создаст её. Если структура журнала запросов изменилась при обновлении сервера ClickHouse, то таблица со старой структурой переименовывается, а новая таблица создается автоматически.
......
......@@ -304,11 +304,11 @@ ClickHouse использует этот параметр при чтении д
**Значение по умолчанию**: 0.
## log_queries
## log_queries {#settings-log-queries}
Установка логгирования запроса.
Запросы, переданные в ClickHouse с этой установкой, логгируются согласно правилам конфигурационного параметра сервера [query_log](../server_settings/settings.md) .
Запросы, переданные в ClickHouse с этой установкой, логгируются согласно правилам конфигурационного параметра сервера [query_log](../server_settings/settings.md#server_settings-query-log).
**Пример** :
......
......@@ -226,6 +226,96 @@ query String - текст запроса. В случае INSERT -
query_id String - идентификатор запроса, если был задан.
```
## system.query_log {#system_tables-query-log}
Содержит логи выполняемых запросов — дату запуска, длительность выполнения, текст возникших ошибок и другую информацию.
!!! note "Внимание"
Таблица не содержит данные, передаваемые в запросах `INSERT`.
Таблица `system.query_log` создаётся только в том случае, если задана серверная настройка [query_log](server_settings/settings.md#server_settings-query-log). Эта настройка определяет правила логирования. Например, с какой периодичностью логи будут записываться в таблицу. Также в этой настройке можно изменить название таблицы.
Чтобы включить логирование запросов, необходимо установить параметр [log_queries](settings/settings.md#settings-log-queries) в 1. Подробнее см. в разделе [Настройки](settings/settings.md).
Логируются следующие запросы:
1. Запросы, которые были вызваны непосредственно клиентом.
2. Дочерние запросы, которые были вызваны другими запросами (при распределенном выполнении запросов). Для дочерних запросов, информация о родительских запросах содержится в столбцах `initial_*`.
Столбцы:
- `type` (UInt8) — тип события, которое возникло при выполнении запроса. Возможные значения:
- 1 — запуск запроса произошел успешно;
- 2 — запрос выполнен успешно;
- 3 — при выполнении запроса возникла ошибка;
- 4 — перед запуском запроса возникла ошибка.
- `event_date` (Date) — дата возникновения события;
- `event_time` (DateTime) — время возникновения события;
- `query_start_time` (DateTime) — время запуска запроса;
- `query_duration_ms` (UInt64) — длительность выполнения запроса;
- `read_rows` (UInt64) — количество прочитанных строк;
- `read_bytes` (UInt64) — количество прочитанных байт;
- `written_rows` (UInt64) — количество записанных строк, для запросов `INSERT`. Для остальных запросов столбец принимает значение 0.
- `written_bytes` (UInt64) — количество записанных байт, для запросов `INSERT`. Для остальных запросов столбец принимает значение 0.
- `result_rows` (UInt64) — количество строк, выведенных в результате;
- `result_bytes` (UInt64) — количество байт, выведенных в результате;
- `memory_usage` (FixedString(16)) — потребление памяти запросом;
- `query` (String) — строка запроса;
- `exception` (String) — сообщение об ошибке;
- `stack_trace` (String) — стектрейс (список методов, которые были вызваны до возникновения ошибки). Пустая строка, если запрос завершился успешно;
- `is_initial_query` (UInt8) — тип запроса:
- 1 — запрос был запущен клиентом;
- 0 — запрос был вызван другим запросом (при распределенном выполнении запросов);
- `user` (String) — имя пользователя, запустившего запрос;
- `query_id` (String) — идентификатор запроса;
- `address` (FixedString(16)) — имя хоста, с которого был отправлен запрос;
- `port` (UInt16) — порт удалённого сервера, принимающего запрос;
- `initial_user` (String) — имя пользователя, вызвавшего родительский запрос (для распределенного выполнения запросов);
- `initial_query_id` (String) — идентификатор родительского запроса, породившего исходный запрос;
- `initial_address` (FixedString(16)) — имя хоста, с которого был вызван родительский запрос;
- `initial_port` (UInt16) — порт удалённого сервера, принимающего родительский запрос;
- `interface` (UInt8) — используемый интерфейс. Возможные значения:
- 1 — TCP.
- 2 — HTTP.
- `os_user` (String) — операционная система на клиенте;
- `client_hostname` (String) — имя хоста, к которому подключен клиент [clickhouse-client](../interfaces/cli.md);
- `client_name` (String) — имя клиента [clickhouse-client](../interfaces/cli.md);
- `client_revision` (UInt32) — ревизия [clickhouse-client](../interfaces/cli.md);
- `client_version_major` (UInt32) — мажорная версия [clickhouse-client](../interfaces/cli.md);
- `client_version_minor` (UInt32) — минорная версия [clickhouse-client](../interfaces/cli.md);
- `client_version_patch` (UInt32) — patch-компонент версии [clickhouse-client](../interfaces/cli.md);
- `http_method` (UInt8) — используемый HTTP-метод. Возможные значения:
- 0 — запрос был вызван из TCP интерфейса;
- 1 — метод `GET`;
- 2 — метод `POST`.
- `http_user_agent` (String) — содержимое заголовка `UserAgent`;
- `quota_key` (String) — ключ квоты, заданный в настройке [quotas](quotas.md);
- `revision` (UInt32) — ревизия сервера ClickHouse;
- `thread_numbers` (Array(UInt32)) — номера потоков, участвующих в выполнении запроса;
- `ProfileEvents.Names` (Array(String)) — счётчики, измеряющие метрики:
- время, потраченное на чтение и запись по сети;
- чтение и запись на диск;
- количество сетевых ошибок;
- время, затраченное на ожидание, при ограниченной пропускной способности сети.
- `ProfileEvents.Values` (Array(UInt64)) — значения счётчиков, перечисленных в `ProfileEvents.Names`.
- `Settings.Names` (Array(String)) — настройки, которые были изменены при выполнении запроса. Чтобы включить отслеживание изменений настроек, установите параметр `log_query_settings` в 1.
- `Settings.Values` (Array(String)) — значения настроек, перечисленных в `Settings.Names`.
Каждый запрос создаёт в таблице `query_log` одно или два события, в зависимости от состояния этого запроса:
1. При успешном выполнении запроса, в таблице создаётся два события с типами 1 и 2 (см. столбец `type`).
2. Если в ходе выполнения запроса возникла ошибка, в таблице создаётся два события с типами 1 и 4.
3. Если ошибка возникла до начала выполнения запроса, создаётся одно событие с типом 3.
По умолчанию, логи записываются в таблицу с периодичностью в 7,5 секунд. Частоту записи логов можно регулировать настройкой [query_log](server_settings/settings.md#server_settings-query-log) (см. параметр `flush_interval_milliseconds`). Чтобы принудительно пробросить логи из буфера памяти в таблицу, используйте запрос `SYSTEM FLUSH LOGS`.
При ручном удалении таблицы, она будет повторно создана на лету. Логи, которые содержались в таблице до её удаления, не сохраняются.
!!! note "Примечание"
Срок хранения логов в таблице неограничен — они не удаляются автоматически. Об удалении неактуальных логов вам нужно позаботиться самостоятельно.
Вы можете задать произвольный ключ партиционирования для таблицы `system.query_log`, в настройке [query_log](server_settings/settings.md#server_settings-query-log) (см. параметр `partition_by`).
## system.replicas {#system_tables-replicas}
Содержит информацию и статус для реплицируемых таблиц, расположенных на локальном сервере.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册