Mysql включить лог ошибок

Если требуется протрейсить запросы к СУБД MySQL (для оптимизации веб-приложений или поиска ошибок), можно включить логирование SQL-запросов в файлы-журналы.

Логи запросов к СУБД MySQL имеют свойство быстро разрастаться, т.к. каждый запрос полностью записывается в файл. Тем самым, на дисковую подсистему ложится большая нагрузка и, в целом, производительность системы и СУБД снижается. Таким образом, включённое логирование запросов — нештатный режим работы СУБД для диагностики, после которой нужно обязательно отключать журналирование.

Создадим директорию, куда будем писать логи MySQL, назначим директории права владельца и группы, от которых работает СУБД (файлы создавать необязательно, они будут созданы автоматически при рестарте демона MySQL).

# mkdir /var/log/mysql
# chown mysql:mysql /var/log/mysql/

Внесём соответствующие директивы в конфигурационный файл my.cnf.

# vi /var/db/mysql/my.cnf
[mysqld]

log=/var/log/mysql/mysql.log                 # Лог всех SQL-запросов
log-bin=/var/log/mysql/mysql.err             # Бинарный лог всех SQL-запросов
log-error=/var/log/mysql/mysql.login         # Лог ошибок в работе демона СУБД MySQL
log-slow-queries=/var/log/mysql/mysql.slow   # Лог всех медленных SQL-запросов
long_query_time=2                            # Кол-во секунд, после которых выполнение запроса считается медленным

Перезагрузим mysqld, чтобы он запустился с новыми директивами логирования.

# /usr/local/etc/rc.d/mysqld restart

Готово. Не забываем после диагностики отключить журналирование.

UPDATE

На MySQL версии 5.6.22 встретилась ошибка:

[ERROR] /usr/local/libexec/mysqld: unknown variable 'log-slow-queries=/var/log/mysql/mysql.slow'

Указываем другие имена директив конфига:

slow-query-log=1
long_query_time=2
slow-query-log-file=/var/log/mysql/mysql.slow

Наверх

В MySQL на данный момент существуют 4 вида журнала (лога) и при достаточно серьёзной работе с базами на MySQL необходимо за ними следить. Например, бинарный лог у нас за сутки набирает около гигабайта, а размер жёсткого диска на сервере ограничен и за ними надо следить. Однако следить следует не только за бинарным логом, так как логи (журналы) в MySQL могут принести немалую пользу.

Итак, какие логи ведёт MySQL? Это:
1. бинарный лог (binary log)
2. лог ошибок (error log)
3. лог медленный запросов (slow query log)
4. лог запросов (general query log)
5. лог репликаций (relay log)

Каждый из них по-своему полезен.

Бинарный лог

В первую очередь полезен с точки зрения репликаций. Можно его бэкапить, можно использовать для восстановления данных на более точное время при использовании бэкапов. Лог содержит все команды изменений базы данных, выборки (select, show) не сохраняет, для таблиц, поддерживающих транзакции (BDB, InnoDB) запись в лог выполняется только после выполнения команды COMMIT. Для лога можно указывать список баз данных, которые надо логировать и список баз данных, которые не надо логировать. В более ранних версиях вместо бинарного лога использовался лог обновлений. Использование бинарного лога снижает производительность базы данных, однако его польза настолько велика, что крайне не рекомендуется его отключать. Рекомендуется защищать бинарный лог паролем, так как он может данные также о паролях пользователей. При достижении максимально разрешённого размера (1 гиг по умолчанию) создаётся следующий файл. Каждый новый файл имеет порядковый номер после имени.

Содержание бинарного лога можно посмотреть с помощью утилиты mysqlbinlog.

Основные настройки в my.cnf

Местоположение лога:
log_bin = /var/log/mysql/mysql-bin.log

Максимальный размер, минимум 4096 байт, по умолчанию 1073741824 байт (1 гигабайт):
max_binlog_size= 500M

Сколько дней хранится:
expire_logs_days = 3

Наиболее часто использующиеся команды

Повторение действий после операции восстановления:
shell> mysqlbinlog log_file | mysql -h server_name

Удаление логов до определённого файла:
PURGE BINARY LOGS TO 'mysql-bin.000';

Удаление логов до определённой даты:
PURGE BINARY LOGS BEFORE 'YYYY-MM-DD hh:mm:ss';

Лог ошибок

Особенно полезен в случаях сбоев. Лог содержит информацию об остановках, запусках сервера, а также сообщения о критических ошибках. Может содержать сообщения с предупреждениями (warnings).

Основные настройки в my.cnf

Местоположение лога:
log_error = /var/log/mysql/mysql.err

Флаг, указывающий стоит ли записывать в лог в том числе предупреждения (записываются, если значение больше нуля):
log_warnings = 1

Наиболее часто использующиеся команды

Переход к новому файл лога:
shell> mysqladmin flush-logs

Копирование старой части лога (необходимо, так как в случае повторного выполнения fluch он будет удалён):
shell> mv host_name.err-old backup-directory

Лог медленных запросов

Если есть подозрение, что приложение работает медленно из-за неэффективных запросов к базе, то в первую очередь следует проверить лог медленных запросов. В случае оптимизации запросов этот лог поможет выяснить, что необходимо оптимизировать в первую очередь.

Основные настройки в my.cnf

Местоположение лога:
log_slow_queries = /var/log/mysql/mysql_slow.log

Со скольки секунд выполнения запрос считается медленным, минимальное значений — 1 секунда, по умолчанию 10 секунд:
long_query_time = 10

Если надо логировать запросы, которые не используют индексы, надо добавить строку:
log-queries-not-using-indexes

Если надо вести лог медленных команд, таких как OPTIMIZE TABLE, ANALYZE TABLE и ALTER TABLE:
log-slow-admin-statements

Лог запросов

Лог содержит информацию о подключениях и отключениях клиентов, а также все SQL запросы, которые были получены. Фактически, это временный лог. Обычно лог удаляется автоматически сразу после выполнения всех команд (т.е. как только он стал ненужным). Лог ведётся в соответствии с очередность поступления запросов. Этот лог содержит все запросы к базе данных (независимо от приложений и пользователей). Так что если есть желание (или необходимость) проанализировать, какие необходимы индексы, какие запросы могли бы оптимизированы, то этот лог как раз может помочь в таких целях. Лог полезен не только для случаев, когда необходимо знать, какие запросы выполняются с базой данных, но и в случаях, когда ясно, что возникла ошибка с базой данных, но неизвестно, какой запрос был отправлен к базе данных (например, в случае генерации динамического SQL-а). Рекомендуется защищать лог запросов паролем, так как он может данные также о паролях пользователей.

Основные настройки в my.cnf

Местоположение лога:
log = /var/log/mysql/mysql.log

Наиболее часто использующиеся команды

В отличии от других логов, перезагрузка сервера и команда fluch не инициирует создание нового лога. Но это можно сделать вручную:
shell> mv host_name.log host_name-old.log
shell> mysqladmin flush-logs
shell> mv host_name-old.log backup-directory

Лог репликаций

Здесь логируются изменения, выполненные по инициации сервера репликаций. Как и бинарный лог, состоит из файлов, каждый из которых пронумерован.

Основные настройки в my.cnf

Местоположение лога:
relay-log = /var/log/mysql/mysql-relay-bin.log

Максимальный размер:
max_relay_log_size = 500М

Наиболее часто использующиеся команды

Начать новый файл лога можно только при остановленном дополнительном (slave) сервере:
shell> cat new_relay_log_name.index >> old_relay_log_name.index
shell> mv old_relay_log_name.index new_relay_log_name.index

Команда fluch logs инициирует ротацию лога.

Всем привет! Заметка будет краткой, так как не хочу открывать лишние вкладки, для того чтобы вспомнить, где и как включать логи. Ниже будет описание о том, какие логи есть (кратко) и как их включить (емко).
Логи в MySQL

Лог ошибок — Error Log

Если необходимо понять, по какой причине не запускается MySql сервер — error log вам в помощь. Там же еще можно прочесть сообщения о том,

По умолчанию все ошибки выводятся в консоль (stderr), в Debian ошибки пишутся в syslog, но по хорошему было бы неплохо вести этот лог в отдельном файле, а именно:

/var/log/mysql/mysql_error.log

Как его перенести?

открыв файл /etc/mysql/my.conf я нашел следующую строчку:

Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf.

Ок, полез в файл /etc/mysql/conf.d/mysqld_safe_syslog.cnf — там следующее содержимое:

[mysqld_safe]
syslog

Поняв, что все льется в syslog, я закомментировал syslog и добавил следующую строку:

log_error=/var/log/mysql/mysql_error.log

Все, логи пишутся куда нужно, и я спокоен.

ps.: Для того, чтобы понять что означают те или иные ошибки, можно воспользоваться такой штукой, как perror.

Двоичный («bin’арный») лог.

В этот лог записываются все команды изменения БД, и нужен он для репликации и восстановления. Включать его не рекомендуется, если никакой репликации не планируется, так как он требователен к ресурсам.

Включается он в файле /etc/mysql/my.conf, там нужно разкомментрировать следующие строки:

log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 5
max_binlog_size = 500M 

Подробнее:

  • log_bin — расположение;
  • expire_logs_days — срок жизни;
  • max_binlog_size — максимальный размер файла.

Лог медленных запросов — mysql-slow.log.

Он будет содержать в себе запросы, которые очень нуждаются в оптимизации. По умолчанию он отключен, включается в том же /etc/mysql/my.cnf.

Если версия MySql у вас < 5.7, то в нужно исправить следующие настройки:

log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 1

Если версия MySql у вас > или = 5.7, то нужно исправить следующие настройки:

slow_query_log = /var/log/mysql/mysql-slow.log
long_query_time = 1

Подробнее:

  • log_slow_queries (slow_query_log) — путь к файлу настроек;
  • long_query_time — минимальное время выполнения запроса в секундах, после которого он считается медленным.

Лог всех запросов.

Пригодиться он опять же для оптимизации и выявления ошибочных запросов, так как записывает все запросы. по умолчанию отключен. Включаем там же: /etc/mysql/my.cnf.

Настройки нужно исправить на подобные:

general_log_file = /var/log/mysql/mysql.log
general_log = 1

Подробнее:

  • general_log_file — месторасположение
  • general_log — включение лога

Включить этот лог «на лету», без перезагрузки, мы можем и из консоли «mysql»:

SET GLOBAL general_log = 'ON';
SET GLOBAL general_log = 'OFF';

Не забываем про logrotate.

Дополнено 04/12/2017…

Как я и обещал в какой-то другой статье — «возможно статья будет дополняться».

Во первых про LogRotate, приведу скрипт который используется у меня:

cat /etc/logrotate.d/mysql-server
# - I put everything in one block and added sharedscripts, so that mysql gets
# flush-logs'd only once.
# Else the binary logs would automatically increase by n times every day.
# - The error log is obsolete, messages go to syslog now.
/var/log/mysql.log /var/log/mysql/mysql.log /var/log/mysql/mysql-slow.log {
daily
rotate 7
missingok
create 640 mysql adm
compress
sharedscripts
postrotate
test -x /usr/bin/mysqladmin || exit 0
# If this fails, check debian.conf!
MYADMIN="/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf"
if [ -z "`$MYADMIN ping 2&gt;/dev/null`" ]; then
# Really no mysqld or rather a missing debian-sys-maint user?
# If this occurs and is not a error please report a bug.
#if ps cax | grep -q mysqld; then
if killall -q -s0 -umysql mysqld; then
exit 1
fi
else
$MYADMIN flush-logs
fi
endscript
}

Как вы уже поняли, он стандартный, и он прекрасно справляется со своей работой.

Нагрузка на БД

Кроме того у меня возникал вопрос: «Скажите пожалуйста какими командами в SSH вычисляется нагрузка на БД ?«..

Собственно все это можно посмотреть хоть в phpmyadmin, но так же никто не запрещает воспользоваться консольным клиентом MySQL, который так и называется: mysql :)

Для того, чтобы в него попасть, необходимо ввести следующую команду, а после пароль

 [[email protected] ]# mysql -u root -p -h localhost
Enter password:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 7926
Server version: 5.0.45 Source distribution

Type 'help;' or 'h' for help. Type 'c' to clear the buffer.

mysql&gt;

все, вы в него попали :)

Там мне были полезны две команды:

show status — команда  предоставляет информацию по состоянию сервера.

Пример ее вывода

mysql&gt; show status;
+-----------------------------------------------+-------------+
| Variable_name                                 | Value       |
+-----------------------------------------------+-------------+
| Aborted_clients                               | 0           |
| Aborted_connects                              | 1           |
| Binlog_cache_disk_use                         | 0           |
| Binlog_cache_use                              | 0           |
| Binlog_stmt_cache_disk_use                    | 0           |
| Binlog_stmt_cache_use                         | 0           |
| Bytes_received                                | 272         |
| Bytes_sent                                    | 509         |
| Com_admin_commands                            | 0           |
| Com_assign_to_keycache                        | 0           |
| Com_alter_db                                  | 0           |
| Com_alter_db_upgrade                          | 0           |
| Com_alter_event                               | 0           |
| Com_alter_function                            | 0           |
| Com_alter_procedure                           | 0           |
| Com_alter_server                              | 0           |
| Com_alter_table                               | 0           |
| Com_alter_tablespace                          | 0           |
| Com_alter_user                                | 0           |
| Com_analyze                                   | 0           |
| Com_begin                                     | 0           |
| Com_binlog                                    | 0           |
| Com_call_procedure                            | 0           |
| Com_change_db                                 | 0           |
| Com_change_master                             | 0           |
| Com_check                                     | 0           |
| Com_checksum                                  | 0           |
| Com_commit                                    | 0           |
| Com_create_db                                 | 0           |
| Com_create_event                              | 0           |
| Com_create_function                           | 0           |
| Com_create_index                              | 0           |
| Com_create_procedure                          | 0           |
| Com_create_server                             | 0           |
| Com_create_table                              | 0           |
| Com_create_trigger                            | 0           |
| Com_create_udf                                | 0           |
| Com_create_user                               | 0           |
| Com_create_view                               | 0           |
| Com_dealloc_sql                               | 0           |
| Com_delete                                    | 0           |
| Com_delete_multi                              | 0           |
| Com_do                                        | 0           |
| Com_drop_db                                   | 0           |
| Com_drop_event                                | 0           |
| Com_drop_function                             | 0           |
| Com_drop_index                                | 0           |
| Com_drop_procedure                            | 0           |
| Com_drop_server                               | 0           |
| Com_drop_table                                | 0           |
| Com_drop_trigger                              | 0           |
| Com_drop_user                                 | 0           |
| Com_drop_view                                 | 0           |
| Com_empty_query                               | 0           |
| Com_execute_sql                               | 0           |
| Com_flush                                     | 0           |
| Com_get_diagnostics                           | 0           |
| Com_grant                                     | 0           |
| Com_ha_close                                  | 0           |
| Com_ha_open                                   | 0           |
| Com_ha_read                                   | 0           |
| Com_help                                      | 0           |
| Com_insert                                    | 0           |
| Com_insert_select                             | 0           |
| Com_install_plugin                            | 0           |
| Com_kill                                      | 0           |
| Com_load                                      | 0           |
| Com_lock_tables                               | 0           |
| Com_optimize                                  | 0           |
| Com_preload_keys                              | 0           |
| Com_prepare_sql                               | 0           |
| Com_purge                                     | 0           |
| Com_purge_before_date                         | 0           |
| Com_release_savepoint                         | 0           |
| Com_rename_table                              | 0           |
| Com_rename_user                               | 0           |
| Com_repair                                    | 0           |
| Com_replace                                   | 0           |
| Com_replace_select                            | 0           |
| Com_reset                                     | 0           |
| Com_resignal                                  | 0           |
| Com_revoke                                    | 0           |
| Com_revoke_all                                | 0           |
| Com_rollback                                  | 0           |
| Com_rollback_to_savepoint                     | 0           |
| Com_savepoint                                 | 0           |
| Com_select                                    | 1           |
| Com_set_option                                | 0           |
| Com_signal                                    | 0           |
| Com_show_binlog_events                        | 0           |
| Com_show_binlogs                              | 0           |
| Com_show_charsets                             | 0           |
| Com_show_collations                           | 0           |
| Com_show_create_db                            | 0           |
| Com_show_create_event                         | 0           |
| Com_show_create_func                          | 0           |
| Com_show_create_proc                          | 0           |
| Com_show_create_table                         | 0           |
| Com_show_create_trigger                       | 0           |
| Com_show_databases                            | 0           |
| Com_show_engine_logs                          | 0           |
| Com_show_engine_mutex                         | 0           |
| Com_show_engine_status                        | 0           |
| Com_show_events                               | 0           |
| Com_show_errors                               | 0           |
| Com_show_fields                               | 0           |
| Com_show_function_code                        | 0           |
| Com_show_function_status                      | 0           |
| Com_show_grants                               | 0           |
| Com_show_keys                                 | 0           |
| Com_show_master_status                        | 0           |
| Com_show_open_tables                          | 0           |
| Com_show_plugins                              | 0           |
| Com_show_privileges                           | 0           |
| Com_show_procedure_code                       | 0           |
| Com_show_procedure_status                     | 0           |
| Com_show_processlist                          | 1           |
| Com_show_profile                              | 0           |
| Com_show_profiles                             | 0           |
| Com_show_relaylog_events                      | 0           |
| Com_show_slave_hosts                          | 0           |
| Com_show_slave_status                         | 0           |
| Com_show_status                               | 1           |
| Com_show_storage_engines                      | 0           |
| Com_show_table_status                         | 0           |
| Com_show_tables                               | 0           |
| Com_show_triggers                             | 0           |
| Com_show_variables                            | 0           |
| Com_show_warnings                             | 0           |
| Com_slave_start                               | 0           |
| Com_slave_stop                                | 0           |
| Com_stmt_close                                | 0           |
| Com_stmt_execute                              | 0           |
| Com_stmt_fetch                                | 0           |
| Com_stmt_prepare                              | 0           |
| Com_stmt_reprepare                            | 0           |
| Com_stmt_reset                                | 0           |
| Com_stmt_send_long_data                       | 0           |
| Com_truncate                                  | 0           |
| Com_uninstall_plugin                          | 0           |
| Com_unlock_tables                             | 0           |
| Com_update                                    | 0           |
| Com_update_multi                              | 0           |
| Com_xa_commit                                 | 0           |
| Com_xa_end                                    | 0           |
| Com_xa_prepare                                | 0           |
| Com_xa_recover                                | 0           |
| Com_xa_rollback                               | 0           |
| Com_xa_start                                  | 0           |
| Compression                                   | OFF         |
| Connection_errors_accept                      | 0           |
| Connection_errors_internal                    | 0           |
| Connection_errors_max_connections             | 0           |
| Connection_errors_peer_address                | 0           |
| Connection_errors_select                      | 0           |
| Connection_errors_tcpwrap                     | 0           |
| Connections                                   | 5           |
| Created_tmp_disk_tables                       | 0           |
| Created_tmp_files                             | 6           |
| Created_tmp_tables                            | 0           |
| Delayed_errors                                | 0           |
| Delayed_insert_threads                        | 0           |
| Delayed_writes                                | 0           |
| Flush_commands                                | 1           |
| Handler_commit                                | 0           |
| Handler_delete                                | 0           |
| Handler_discover                              | 0           |
| Handler_external_lock                         | 0           |
| Handler_mrr_init                              | 0           |
| Handler_prepare                               | 0           |
| Handler_read_first                            | 0           |
| Handler_read_key                              | 0           |
| Handler_read_last                             | 0           |
| Handler_read_next                             | 0           |
| Handler_read_prev                             | 0           |
| Handler_read_rnd                              | 0           |
| Handler_read_rnd_next                         | 0           |
| Handler_rollback                              | 0           |
| Handler_savepoint                             | 0           |
| Handler_savepoint_rollback                    | 0           |
| Handler_update                                | 0           |
| Handler_write                                 | 0           |
| Innodb_buffer_pool_dump_status                | not started |
| Innodb_buffer_pool_load_status                | not started |
| Innodb_buffer_pool_pages_data                 | 323         |
| Innodb_buffer_pool_bytes_data                 | 5292032     |
| Innodb_buffer_pool_pages_dirty                | 0           |
| Innodb_buffer_pool_bytes_dirty                | 0           |
| Innodb_buffer_pool_pages_flushed              | 1           |
| Innodb_buffer_pool_pages_free                 | 7866        |
| Innodb_buffer_pool_pages_misc                 | 2           |
| Innodb_buffer_pool_pages_total                | 8191        |
| Innodb_buffer_pool_read_ahead_rnd             | 0           |
| Innodb_buffer_pool_read_ahead                 | 0           |
| Innodb_buffer_pool_read_ahead_evicted         | 0           |
| Innodb_buffer_pool_read_requests              | 2642        |
| Innodb_buffer_pool_reads                      | 324         |
| Innodb_buffer_pool_wait_free                  | 0           |
| Innodb_buffer_pool_write_requests             | 1           |
| Innodb_data_fsyncs                            | 5           |
| Innodb_data_pending_fsyncs                    | 0           |
| Innodb_data_pending_reads                     | 0           |
| Innodb_data_pending_writes                    | 0           |
| Innodb_data_read                              | 5378048     |
| Innodb_data_reads                             | 336         |
| Innodb_data_writes                            | 5           |
| Innodb_data_written                           | 34304       |
| Innodb_dblwr_pages_written                    | 1           |
| Innodb_dblwr_writes                           | 1           |
| Innodb_have_atomic_builtins                   | ON          |
| Innodb_log_waits                              | 0           |
| Innodb_log_write_requests                     | 0           |
| Innodb_log_writes                             | 1           |
| Innodb_os_log_fsyncs                          | 3           |
| Innodb_os_log_pending_fsyncs                  | 0           |
| Innodb_os_log_pending_writes                  | 0           |
| Innodb_os_log_written                         | 512         |
| Innodb_page_size                              | 16384       |
| Innodb_pages_created                          | 0           |
| Innodb_pages_read                             | 323         |
| Innodb_pages_written                          | 1           |
| Innodb_row_lock_current_waits                 | 0           |
| Innodb_row_lock_time                          | 0           |
| Innodb_row_lock_time_avg                      | 0           |
| Innodb_row_lock_time_max                      | 0           |
| Innodb_row_lock_waits                         | 0           |
| Innodb_rows_deleted                           | 0           |
| Innodb_rows_inserted                          | 0           |
| Innodb_rows_read                              | 0           |
| Innodb_rows_updated                           | 0           |
| Innodb_num_open_files                         | 5           |
| Innodb_truncated_status_writes                | 0           |
| Innodb_available_undo_logs                    | 128         |
| Key_blocks_not_flushed                        | 0           |
| Key_blocks_unused                             | 13396       |
| Key_blocks_used                               | 0           |
| Key_read_requests                             | 0           |
| Key_reads                                     | 0           |
| Key_write_requests                            | 0           |
| Key_writes                                    | 0           |
| Last_query_cost                               | 0.000000    |
| Last_query_partial_plans                      | 0           |
| Max_used_connections                          | 1           |
| Not_flushed_delayed_rows                      | 0           |
| Open_files                                    | 16          |
| Open_streams                                  | 0           |
| Open_table_definitions                        | 67          |
| Open_tables                                   | 60          |
| Opened_files                                  | 115         |
| Opened_table_definitions                      | 0           |
| Opened_tables                                 | 0           |
| Performance_schema_accounts_lost              | 0           |
| Performance_schema_cond_classes_lost          | 0           |
| Performance_schema_cond_instances_lost        | 0           |
| Performance_schema_digest_lost                | 0           |
| Performance_schema_file_classes_lost          | 0           |
| Performance_schema_file_handles_lost          | 0           |
| Performance_schema_file_instances_lost        | 0           |
| Performance_schema_hosts_lost                 | 0           |
| Performance_schema_locker_lost                | 0           |
| Performance_schema_mutex_classes_lost         | 0           |
| Performance_schema_mutex_instances_lost       | 0           |
| Performance_schema_rwlock_classes_lost        | 0           |
| Performance_schema_rwlock_instances_lost      | 0           |
| Performance_schema_session_connect_attrs_lost | 0           |
| Performance_schema_socket_classes_lost        | 0           |
| Performance_schema_socket_instances_lost      | 0           |
| Performance_schema_stage_classes_lost         | 0           |
| Performance_schema_statement_classes_lost     | 0           |
| Performance_schema_table_handles_lost         | 0           |
| Performance_schema_table_instances_lost       | 0           |
| Performance_schema_thread_classes_lost        | 0           |
| Performance_schema_thread_instances_lost      | 0           |
| Performance_schema_users_lost                 | 0           |
| Prepared_stmt_count                           | 0           |
| Qcache_free_blocks                            | 1           |
| Qcache_free_memory                            | 16759680    |
| Qcache_hits                                   | 0           |
| Qcache_inserts                                | 0           |
| Qcache_lowmem_prunes                          | 0           |
| Qcache_not_cached                             | 1           |
| Qcache_queries_in_cache                       | 0           |
| Qcache_total_blocks                           | 1           |
| Queries                                       | 8           |
| Questions                                     | 3           |
| Select_full_join                              | 0           |
| Select_full_range_join                        | 0           |
| Select_range                                  | 0           |
| Select_range_check                            | 0           |
| Select_scan                                   | 0           |
| Slave_heartbeat_period                        |             |
| Slave_last_heartbeat                          |             |
| Slave_open_temp_tables                        | 0           |
| Slave_received_heartbeats                     |             |
| Slave_retried_transactions                    |             |
| Slave_running                                 | OFF         |
| Slow_launch_threads                           | 0           |
| Slow_queries                                  | 0           |
| Sort_merge_passes                             | 0           |
| Sort_range                                    | 0           |
| Sort_rows                                     | 0           |
| Sort_scan                                     | 0           |
| Ssl_accept_renegotiates                       | 0           |
| Ssl_accepts                                   | 0           |
| Ssl_callback_cache_hits                       | 0           |
| Ssl_cipher                                    |             |
| Ssl_cipher_list                               |             |
| Ssl_client_connects                           | 0           |
| Ssl_connect_renegotiates                      | 0           |
| Ssl_ctx_verify_depth                          | 0           |
| Ssl_ctx_verify_mode                           | 0           |
| Ssl_default_timeout                           | 0           |
| Ssl_finished_accepts                          | 0           |
| Ssl_finished_connects                         | 0           |
| Ssl_server_not_after                          |             |
| Ssl_server_not_before                         |             |
| Ssl_session_cache_hits                        | 0           |
| Ssl_session_cache_misses                      | 0           |
| Ssl_session_cache_mode                        | NONE        |
| Ssl_session_cache_overflows                   | 0           |
| Ssl_session_cache_size                        | 0           |
| Ssl_session_cache_timeouts                    | 0           |
| Ssl_sessions_reused                           | 0           |
| Ssl_used_session_cache_entries                | 0           |
| Ssl_verify_depth                              | 0           |
| Ssl_verify_mode                               | 0           |
| Ssl_version                                   |             |
| Table_locks_immediate                         | 70          |
| Table_locks_waited                            | 0           |
| Table_open_cache_hits                         | 0           |
| Table_open_cache_misses                       | 0           |
| Table_open_cache_overflows                    | 0           |
| Tc_log_max_pages_used                         | 0           |
| Tc_log_page_size                              | 0           |
| Tc_log_page_waits                             | 0           |
| Threads_cached                                | 0           |
| Threads_connected                             | 1           |
| Threads_created                               | 1           |
| Threads_running                               | 1           |
| Uptime                                        | 147542      |
| Uptime_since_flush_status                     | 147542      |
+-----------------------------------------------+-------------+
341 rows in set (0,00 sec) 

Подробное описание команды

Команда SHOW STATUS предоставляет информацию по состоянию сервера (как mysqladmin extended-status). Приведенные выше переменные состояния имеют следующие значения:

  • Aborted_clients — Количество соединений, отмененных по причине отключения клиента без надлежащего закрытия соединения. See Раздел A.2.9, «Коммуникационные ошибки / Оборванные соединения».
  • Aborted_connects — Количество неудачных попыток подсоединения к серверу MySQL. See Раздел A.2.9, «Коммуникационные ошибки / Оборванные соединения».
  • Bytes_received — Количество байтов, полученных от всех клиентов.
  • Bytes_sent — Количество байтов, отправленных всем клиентам.
  • Com_xxx — Количество запусков каждой команды xxx.
  • Connections — Количество попыток подсоединения к серверу MySQL.
  • Created_tmp_tables — Количество неявных временных таблиц на диске, созданных во время выполнения операторов.
  • Created_tmp_tables — Количество неявных временных таблиц в памяти, созданных во время выполнения операторов.
  • Created_tmp_files — Количество созданных временных файлов mysqld.
  • Delayed_insert_threads — Количество используемых потоков вставки данных в режиме insert delayed.
  • Delayed_writes — Количество строк, вставленных при помощи команды INSERT DELAYED.
  • Delayed_errors — Количество записанных при помощи команды INSERT DELAYED строк, в которых произошли какие-либо ошибки (возможно, duplicate key).
  • Flush_commands — Количество запущенных команд FLUSH.
  • Handler_commit — Количество внутренних команд COMMIT.
  • Handler_delete — Количество удалений строки из таблицы.
  • Handler_read_first — Количество считываний из индекса первой записи. Если это значение высокое, то, по всей вероятности, сервер осуществляет много полных индексных сканирований, например, SELECT col1 FROM foo, предполагая, что col1 проиндексирован.
  • Handler_read_key — Количество запросов на чтение строки, основанных на ключе. Высокое значение переменной говорит о том, что ваши запросы и таблицы проиндексированы надлежащим образом.
  • Handler_read_next — Количество запросов на чтение следующей строки в порядке расположения ключей. Это значение будет увеличиваться, если производится запрос индексного столбца с ограничением по размеру. Значение также увеличивается во время проведения индексного сканирования.
  • Handler_read_prev — Количество запросов на чтение предыдущей строки в порядке расположения ключей. В большинстве случаев используется для оптимизации ORDER BY … DESC.
  • Handler_read_rnd — Количество запросов на чтение строки, основанных на фиксированной позиции. Значение будет высоким, если выполняется много запросов, требующих сортировки результатов.
  • Handler_read_rnd_next — Количество запросов на чтение следующей строки из файла данных. Данное значение будет высоким, если производится много сканирований таблиц. Обычно это означает, что ваши таблицы не проиндексированы надлежащим образом или ваши запросы не используют преимущества индексов.
  • Handler_rollback — Количество внутренних команд ROLLBACK.
  • Handler_update — Количество запросов на обновление строки в таблице.
  • Handler_write — Количество запросов на вставку строки в таблицу.
  • Key_blocks_used — Количество используемых блоков в кэше ключей.
  • Key_read_requests — Количество запросов на чтение блока ключей из кэша.
  • Key_reads — Количество физических считываний блока ключей с диска.
  • Key_write_requests — Количество запросов на запись блока ключей в кэш.
  • Key_writes — Количество физических записей блоков ключей на диск.
  • Max_used_connections — Максимальное количество одновременно используемых соединений.
  • Not_flushed_key_blocks — Блоки ключей в кэше ключей, которые были изменены, но еще не записаны на диск.
  • Not_flushed_delayed_rows — Количество строк, стоящих в очереди на запись в запросах INSERT DELAY.
  • Open_tables — Количество открытых таблиц.
  • Open_files — Количество открытых файлов.
  • Open_streams — Количество открытых потоков (в основном используется для журналирования).
  • Opened_tables — Количество открывавшихся таблиц.
  • Rpl_status — Статус отказобезопасной репликации (еще не используется).
  • Select_full_join — Количество соединений без ключей (если это значение равно 0, необходимо внимательно проверить индексы своих таблиц).
  • Select_full_range_join — Количество соединений, где был использован поиск по диапазону в справочной таблице.
  • Select_range — Количество соединений, в которых использовались диапазоны в первой таблице. (Обычно это значение не критично, даже если оно велико)
    Select_scan — Количество соединений, в которых проводилось первое сканирование первой таблицы.
  • Select_range_check — Количество соединений без ключей, в которых проверка использования ключей производится после каждой строки (если это значение равно 0, необходимо внимательно проверить индексы своих таблиц).
  • Questions — Количество запросов, направленных на сервер.
  • Slave_open_temp_tables — Количество временных таблиц, открытых в настоящий момент потоком подчиненного компьютера.
  • Slave_running — Содержит значение ON, если это подчиненный компьютер, подключенный к головному компьютеру.
  • Slow_launch_threads — Количество потоков, создание которых заняло больше, чем указано в slow_launch_time.
  • Slow_queries — Количество запросов, обработка которых заняла больше времени, чем long_query_time. See Раздел 4.9.5, «Журнал медленных запросов».
  • Sort_merge_passes — Количество объединений, осуществленных алгоритмом сортировки. Если это значение велико, следует увеличить sort_buffer_size.
  • Sort_range — Количество сортировок, которые осуществлялись в диапазонах.
  • Sort_rows — Количество отсортированных строк.
  • Sort_scan — Количество сортировок, осуществленных путем сканирования таблицы.
  • ssl_xxx — Переменные, используемые SSL; еще не реализовано.
  • Table_locks_immediate — Количество запросов на немедленную блокировку таблицы. Доступно начиная с версии 3.23.33.
  • Table_locks_waited — Количество запросов, когда немедленная блокировка не могла быть осуществлена и требовалось время на ожидание. Если это значение велико, и у вас есть проблемы с производительностью, сначала необходимо оптимизировать свои запросы, а затем либо разделить таблицы, либо использовать репликацию. Доступно начиная с версии 3.23.33.
  • Threads_cached — Количество потоков в кэше потоков.
  • Threads_connected — Количество открытых в настоящий момент соединений.
  • Threads_created — Количество потоков, созданных для управления соединениями.
  • Threads_running — Количество не простаивающих потоков.
  • Uptime — Время в секундах, в течение которого сервер находится в работе.

Некоторые примечания к приведенной выше информации:

  • Если значение Opened_tables велико, возможно, что значение переменной table_cache слишком мало.
  • Если значение Key_reads велико, возможно, что значение переменной key_buffer_size слишком мало. Частоту неуспешных обращений к кэшу можно вычислить так: Key_reads/Key_read_requests.
  • Если значение Handler_read_rnd велико, возможно, поступает слишком много запросов, требующих от MySQL полного сканирования таблиц или у вас есть соединения, которые не используют ключи надлежащим образом.
  • Если значение Threads_created велико, возможно, необходимо увеличить значение переменной thread_cache_size. Частоту успешных обращений к кэшу можно вычислить при помощи Threads_created/Connections.
  • Если значение Created_tmp_disk_tables велико, возможно, необходимо увеличить значение переменной tmp_table_size, чтобы временные таблицы располагались в памяти, а не на жестком диске.

show processlist — показывает, какие потоки запущены в настоящий момент. Пример ее вывода:

mysql&gt; show processlist;
+----+------+-----------+------+---------+------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+----+------+-----------+------+---------+------+-------+------------------+
| 4 | root | localhost | NULL | Query | 0 | init | show processlist |
+----+------+-----------+------+---------+------+-------+------------------+
1 row in set (0,00 sec) 

Подробное описание команды

Команда SHOW [FULL] PROCESSLIST показывает, какие потоки запущены в настоящий момент. Эту информацию также можно получить при помощи команды mysqladmin processlist. Если у вас привилегия SUPER, можно просматривать все потоки, в противном случае — только свои потоки. See Раздел 4.5.5, «Синтаксис команды KILL». Если не используется параметр FULL, будут показаны только первые 100 символов каждого запроса.

Начиная с 4.0.12, MySQL сообщает имя хоста для TCP/IP соединений как имя_хоста:клиентский_порт с тем, чтобы было проще понять, какой клиент чем занят.

Эта команда очень полезна, если выдается сообщение об ошибке ‘too many connections’ (слишком много соединений) и необходимо выяснить, что происходит. MySQL резервирует одно дополнительное соединение для клиента с привилегией SUPER, чтобы у вас всегда была возможность войти в систему и произвести проверку (предполагается, что вы не станете раздавать эту привилегию всем своим пользователям).

Некоторые состояния обычно можно увидеть в mysqladmin processlist.

  • Checking table — Поток осуществляет [автоматическую] проверку таблицы.
  • Closing tables — Означает, что поток записывает измененные данные таблиц на диск и закрывает использующиеся таблицы. Выполнение этой операции должно произойти быстро. Если на нее уходит значительное время, убедитесь, что диск не переполнен или что диск не используется слишком интенсивно.
  • Connect Out — Подчиненный компьютер, подсоединенный к головному компьютеру.
  • Copying to tmp table on disk — Набор временных результатов превысил tmp_table_size, и теперь поток изменяет таблицу временных данных, расположенную в памяти, на дисковую таблицу, чтобы сохранить память.
  • Creating tmp table — Поток создает временную таблицу, чтобы хранить часть результатов для запроса.
  • deleting from main table — При запуске первой части удаления нескольких таблиц удаление производится только начиная с первой таблицы.
  • deleting from reference tables — При запуске второй части удаления нескольких таблиц удаляются совпадающие строки из других таблиц.
  • Flushing tables — Поток запускает команду FLUSH TABLES и ожидает, пока все потоки закроют свои таблицы.
  • Killed — Кто-то направил команду на закрытие потока, и поток будет закрыт при следующей проверке флага закрытия. Флаг проверяется при каждом основном цикле в MySQL, но в некоторых случаях закрытие потока может занять некоторое время. Если поток заблокирован другим потоком, закрытие будет произведено сразу после того, как другой поток снимет блокировку.
  • Sending data — Поток обрабатывает строки для оператора SELECT, а также направляет данные клиенту.
  • Sorting for group — Поток осуществляет сортировку в соответствии с GROUP BY.
  • Sorting for order — Поток осуществляет сортировку в соответствии с ORDER BY.
  • Opening tables — Это просто означает, что поток пытается открыть таблицу. Такая процедура осуществляется довольно быстро, если что-либо не мешает открытию. Например, команды ALTER TABLE или LOCK TABLE могут помешать открытию таблицы, пока выполнение команды не будет завершено.
  • Removing duplicates — Запрос использовал команду SELECT DISTINCT таким образом, что MySQL не смог произвести оптимизацию на начальном этапе. Поэтому MySQL перед отправкой результатов клиенту должен выполнить дополнительное удаление всех дублирующихся строк.
  • Reopen table — Поток заблокировал таблицу, но обнаружил, что после блокировки структура таблицы изменилась. Он снял блокировку, закрыл таблицу и теперь пытается повторно ее открыть.
  • Repair by sorting — Код восстановления использует сортировку для создания индексов.
  • Repair with keycache — Код восстановления использует создание ключей один за другим, через кэш ключей. Это намного медленнее, чем Repair by sorting.
  • Searching rows for update — Поток осуществляет первую фазу — производит поиск всех совпадающих строк, чтобы затем обновить их. Это действие
    необходимо выполнить, если команда UPDATE изменяет индекс, который используется для поиска указанных строк.
  • Sleeping — Поток ожидает, когда клиент направит ему новую команду.
  • System lock — Поток ожидает получения внешней системной блокировки таблицы. Если не используется несколько серверов mysqld, которые получают доступ к одним и тем же таблицам, системную блокировку можно отключить при помощи параметра —skip-external-locking.
  • Upgrading lock — Обработчик INSERT DELAYED пытается заблокировать таблицу, чтобы вставить строки.
  • Updating — Поток производит поиск строк, которые необходимо обновить, и обновляет их.
  • User Lock — Поток ожидает GET_LOCK().
  • Waiting for tables — Поток получил уведомление, что структура таблицы изменилась, и ему необходимо повторно открыть таблицу, чтобы получить новую структуру. Чтобы повторно открыть таблицу, он должен подождать, пока ее не закроют все остальные потоки. Это уведомление выдается, если другой поток воспользовался командой FLUSH TABLES или к таблице была применена одна из следующих команд: FLUSH TABLES table_name, ALTER TABLE, RENAME TABLE, REPAIR TABLE, ANALYZE TABLE или OPTIMIZE TABLE. Обработчик INSERT DELAYED завершил работу со всеми вставками и ожидает новые.

Большинство состояний — это очень быстрые операции. Если потоки остаются в любом из этих состояний на протяжении большого количества секунд, то, возможно, возникла какая-то проблема, которую следует устранить.

Существует еще несколько состояний, не упомянутых выше, но большинство из них полезны только для поиска ошибок в mysqld.

Описания я взял с руководства, возможно немного не актуального, но на первых парах описаны все основные моменты. Остальное — смотрим полные версии руководства.

Источники:

  • https://ruhighload.com/post/бла-бла-бла-1
  • https://ruhighload.com/post/бла-бла-бла-2
  • https://dev.mysql.com/doc/refman/5.7/en/perror.html
  • https://unixforum.org/index.php?showtopic=92923
  • http://www.arininav.ru/mysql/show-status.html
  • http://www.arininav.ru/mysql/show-processlist.html

How do I enable the MySQL function that logs each SQL query statement received from clients and the time that query statement has submitted?
Can I do that in phpmyadmin or NaviCat?
How do I analyse the log?

OrangeTux's user avatar

OrangeTux

11.1k7 gold badges48 silver badges73 bronze badges

asked Jun 25, 2011 at 16:41

Feng-Chun Ting's user avatar

Feng-Chun TingFeng-Chun Ting

3,3413 gold badges17 silver badges11 bronze badges

First, Remember that this logfile can grow very large on a busy server.

For mysql < 5.1.29:

To enable the query log, put this in /etc/my.cnf in the [mysqld] section

log   = /path/to/query.log  #works for mysql < 5.1.29

Also, to enable it from MySQL console

SET general_log = 1;

See http://dev.mysql.com/doc/refman/5.1/en/query-log.html

For mysql 5.1.29+

With mysql 5.1.29+ , the log option is deprecated. To specify the logfile and enable logging, use this in my.cnf in the [mysqld] section:

general_log_file = /path/to/query.log
general_log      = 1

Alternately, to turn on logging from MySQL console (must also specify log file location somehow, or find the default location):

SET global general_log = 1;

Also note that there are additional options to log only slow queries, or those which do not use indexes.

Firze's user avatar

Firze

3,8916 gold badges48 silver badges61 bronze badges

answered Jun 25, 2011 at 16:54

Gryphius's user avatar

7

Take a look on this answer to another related question. It shows how to enable, disable and to see the logs on live servers without restarting.

Log all queries in mysql


Here is a summary:

If you don’t want or cannot restart the MySQL server you can proceed like this on your running server:

  • Create your log tables (see answer)

  • Enable Query logging on the database
    (Note that the string ‘table’ should be put literally and not substituted by any table name. Thanks Nicholas Pickering)

SET global general_log = 1;
SET global log_output = 'table';
  • View the log
select * from mysql.general_log;
  • Disable Query logging on the database
SET global general_log = 0;
  • Clear query logs without disabling
TRUNCATE mysql.general_log

Archimedes Trajano's user avatar

answered Jan 18, 2013 at 17:09

Alexandre Marcondes's user avatar

3

This was already in a comment, but deserves its own answer:
Without editing the config files: in mysql, as root, do

SET global general_log_file='/tmp/mysql.log'; 
SET global log_output = 'file';
SET global general_log = on;

Don’t forget to turn it off afterwards:

SET global general_log = off;

panepeter's user avatar

panepeter

3,0851 gold badge29 silver badges40 bronze badges

answered Apr 3, 2017 at 13:38

commonpike's user avatar

commonpikecommonpike

10.3k4 gold badges65 silver badges58 bronze badges

6

I use this method for logging when I want to quickly optimize different page loads.
It’s a little tip…

Logging to a TABLE

SET global general_log = 1;
SET global log_output = 'table';

You can then select from my mysql.general_log table to retrieve recent queries.

I can then do something similar to tail -f on the mysql.log, but with more refinements…

select * from mysql.general_log 
where  event_time  > (now() - INTERVAL 8 SECOND) and thread_id not in(9 , 628)
and argument <> "SELECT 1" and argument <> "" 
and argument <> "SET NAMES 'UTF8'"  and argument <> "SHOW STATUS"  
and command_type = "Query"  and argument <> "SET PROFILING=1"

This makes it easy to see my queries that I can try and cut back. I use 8 seconds interval to only fetch queries executed within the last 8 seconds.

answered Feb 16, 2014 at 13:46

Layke's user avatar

LaykeLayke

50.9k11 gold badges85 silver badges111 bronze badges

You can disable or enable the general query log (which logs all queries) with

SET GLOBAL general_log = 1 # (or 0 to disable)

answered Jun 25, 2011 at 17:37

Jon's user avatar

JonJon

427k80 gold badges735 silver badges804 bronze badges

1

// To see global variable is enabled or not and location of query log    
SHOW VARIABLES like 'general%';
// Set query log on 
SET GLOBAL general_log = ON; 

ahajib's user avatar

ahajib

12.7k28 gold badges79 silver badges116 bronze badges

answered May 8, 2019 at 19:10

Sameer Kumar Choudhary's user avatar

I also wanted to enable the MySQL log file to see the queries and I have resolved this with the below instructions

  1. Go to /etc/mysql/mysql.conf.d
  2. open the mysqld.cnf

and enable the below lines

general_log_file        = /var/log/mysql/mysql.log
general_log             = 1
  1. restart the MySQL with this command /etc/init.d/mysql restart
  2. go to /var/log/mysql/ and check the logs

Sumithran's user avatar

Sumithran

6,1494 gold badges39 silver badges53 bronze badges

answered Jun 21, 2017 at 12:48

shrikant's user avatar

shrikantshrikant

4325 silver badges11 bronze badges

1

On Windows you can simply go to

C:wampbinmysqlmysql5.1.53my.ini

Insert this line in my.ini

general_log_file = c:/wamp/logs/mysql_query_log.log

The my.ini file finally looks like this

...
...
...    
socket      = /tmp/mysql.sock
skip-locking
key_buffer = 16M
max_allowed_packet = 1M
table_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
basedir=c:/wamp/bin/mysql/mysql5.1.53
log = c:/wamp/logs/mysql_query_log.log        #dump query logs in this file
log-error=c:/wamp/logs/mysql.log
datadir=c:/wamp/bin/mysql/mysql5.1.53/data
...
...
...
...

answered Apr 4, 2014 at 7:09

HimalayanCoder's user avatar

HimalayanCoderHimalayanCoder

9,5306 gold badges59 silver badges60 bronze badges

There is bug in MySQL 5.6 version.
Even mysqld show as :

    Default options are read from the following files in the given order:
C:Windowsmy.ini C:Windowsmy.cnf C:my.ini C:my.cnf c:Program Files (x86)MySQLMySQL Server 5.6my.ini c:Program Files (x86)MySQLMySQL Server 5.6my.cnf 

Realy settings are reading in following order :

    Default options are read from the following files in the given order:
C:ProgramDataMySQLMySQL Server 5.6my.ini C:Windowsmy.ini C:Windowsmy.cnf C:my.ini C:my.cnf c:Program Files (x86)MySQLMySQL Server 5.6my.ini c:Program Files (x86)MySQLMySQL Server 5.6my.cnf

Check file: «C:ProgramDataMySQLMySQL Server 5.6my.ini»

Hope it help somebody.

answered Mar 30, 2015 at 20:38

croonx's user avatar

croonxcroonx

1391 silver badge6 bronze badges

1

for mysql>=5.5 only for slow queries (1 second and more)
my.cfg

[mysqld]
slow-query-log = 1
slow-query-log-file = /var/log/mysql/mysql-slow.log
long_query_time = 1
log-queries-not-using-indexes

answered Dec 9, 2014 at 23:19

Alies's user avatar

AliesAlies

5995 silver badges11 bronze badges

2

To enable the query log in MAC Machine:

Open the following file:

vi /private/etc/my.cnf

Set the query log url under ‘mysqld’ section as follows:

[mysqld]

general_log_file=/Users/kumanan/Documents/mysql_query.log

Few machine’s are not logging query properly, So that case you can enable it from MySQL console

mysql> SET global general_log = 1;

answered Jan 27, 2016 at 12:48

Kumanan's user avatar

KumananKumanan

4101 gold badge4 silver badges10 bronze badges

Not exactly an answer to the question because the question already has great answers. This is a side info. Enabling general_log really put a dent on MySQL performance. I left general_log =1 accidentally on a production server and spent hours finding out why performance was not comparable to a similar setup on other servers. Then I found this which explains the impact of enabling general log. http://www.fromdual.com/general_query_log_vs_mysql_performance.

Gist of the story, don’t put general_log=1 in the .cnf file. Instead use set global general_log =1 for a brief duration just to log enough to find out what you are trying to find out and then turn it off.

answered Apr 22, 2017 at 16:41

Allen King's user avatar

Allen KingAllen King

2,3424 gold badges33 silver badges49 bronze badges

In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.

answered Aug 23, 2013 at 19:34

Marc Delisle's user avatar

Marc DelisleMarc Delisle

8,8793 gold badges28 silver badges29 bronze badges

I had to drop and recreate the general log at one point. During the recreation, character sets got messed up and I ended up having this error in the logs:

[ERROR] Incorrect definition of table mysql.general_log: expected the type of column 'user_host' at position 1 to have character set 'utf8' but found character set 'latin1'

So if the standard answer of «check to make sure logging is on» doesn’t work for you, check to make sure your fields have the right character set.

answered Jun 11, 2017 at 21:37

William Neely's user avatar

William NeelyWilliam Neely

1,8901 gold badge20 silver badges22 bronze badges

My OS Win10, MySQL server version — 5.7

The path to my.ini

C:ProgramDataMySQLMySQL Server 5.7my.ini

Just add into my.ini file

general_log_file        = C:/ProgramData/MySQL/MySQL Server 5.7/mysql.log
general_log             = 1

answered Dec 2, 2021 at 9:19

Dmitriy S's user avatar

Dmitriy SDmitriy S

3511 gold badge4 silver badges14 bronze badges

You may come across a set of Hexadecimal values, like this (argument column):

mysql> select * from mysql.general_log LIMIT 1G
*************************** 1. row ***************************
  event_time: 2023-01-27 13:37:20.950778
   user_host: root[root] @ localhost []
   thread_id: 1434
   server_id: 1
command_type: Query
    argument: 0x73656C656374202A2066726F6D207573657273
1 row in set (0.00 sec)

so to make it readable, just use:

select a.*, convert(a.argument using utf8) from mysql.general_log a;

And the return is something like this:

mysql> select a.*, convert(a.argument using utf8) from mysql.general_log a LIMIT 1G
*************************** 1. row ***************************
                    event_time: 2023-01-27 13:37:20.950778
                     user_host: root[root] @ localhost []
                     thread_id: 1434
                     server_id: 1
                  command_type: Query
                      argument: 0x73656C656374202A2066726F6D207573657273
convert(a.argument using utf8): select * from users
1 row in set, 1 warning (0.00 sec)

Ps: I used LIMIT 1 on examples, because my log table is too big.

answered Jan 27 at 18:56

Paulo Nahes's user avatar

This tutorial shows you how to configure and view different MySQL logs. MySQL is
an open-source relational database based on SQL (Structured Query Language).
MySQL offers various built-in logs. In general, a database is the cornerstone of
almost every backend, and because of that administrators want to log this
service.

MySQL has multiple logs with different purpose. We will focus on following four
logs:

  • Error log: Records problems encountered starting, running, or stopping
    mysqld. This log is stored by default in the /var/log directory. It could
    be useful if you want to analyze the server itself.
  • General query logs: Records every connection established with each client.
    This log records everything that client sent to the server. This log is useful
    to determine client problems.
  • Binary logs: Record each event that manipulates data in the database.
    These log records operations such as a table creating, modification of schema,
    inserting new values, or querying tables. These logs are used to backup and
    recover the database.
  • Slow query log: Record of each query, which execution took too much time.
    This log could be useful for the optimisation of slow SQL queries.

In this tutorial, you will do the following actions:

  • You will install the MySQL server and view default error log.
  • You will connect to MySQL server, view metadata about general query logs
    and view these logs.
  • You will understand the concept of the MySQL binary logs and where to find
    them.
  • You will enable and configure a slow query log, simulate some slow query
    and check this incident in the new log.

🔭 Want to centralize and monitor your MySQL logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

Prerequisites

You will need:

  • Ubuntu 20.04 distribution including the non-root user with sudo access.
  • Basic knowledge of SQL languages (understanding of simple select query
    statement).

Step 1 — Viewing Error Log

The MySQL server is maintained by the command-line program mysqld. This
program manages access to the MySQL data directory that contains databases and
tables. The problems encountered during mysqld starting, running, or stopping
are stored as a custom log in the directory /var/log/mysql. This log doesn’t
include any information about SQL queries. It is useful for the analysis of the
MySQL server.

First of all, let’s install the MySQL server. Ubuntu 20.04 allows to install the
MySQL from default packages with the apt install (installation requires sudo
privilege):

$ sudo apt update
$ sudo apt install mysql-server

The first command will update Ubuntu repositories, and the second will download
and install required packages for the MySQL server.

Now, the server is installed. The new service already creates a default error
log. You can list the directory /var/log and find a new subdirectory mysql
with ls:

You’ll see the program’s output appear on the screen:

Output
alternatives.log       bootstrap.log           kern.log.4.gz
alternatives.log.1     btmp                    lastlog
alternatives.log.2.gz  btmp.1                  letsencrypt
alternatives.log.3.gz  cups                    my-custom-app
apache2                dist-upgrade            mysql
apport.log             dmesg                   openvpn
apport.log.1           dmesg.0                 private
apport.log.2.gz        dmesg.1.gz              speech-dispatcher
apport.log.3.gz        dmesg.2.gz              syslog
apport.log.4.gz        dmesg.3.gz              syslog.1
apport.log.5.gz        dmesg.4.gz              syslog.2.gz
apport.log.6.gz        dpkg.log                syslog.3.gz
apport.log.7.gz        dpkg.log.1              syslog.4.gz
apt                    dpkg.log.2.gz           syslog.5.gz
auth.log               dpkg.log.3.gz           syslog.6.gz
auth.log.1             faillog                 syslog.7.gz
auth.log.2.gz          fontconfig.log          teamviewer15
auth.log.3.gz          gdm3                    test.log
auth.log.4.gz          gpu-manager.log         ubuntu-advantage.log
boot.log               gpu-manager-switch.log  unattended-upgrades
boot.log.1             hp                      wtmp
boot.log.2             installer               wtmp.1
boot.log.3             journal                 Xorg.0.log
boot.log.4             kern.log                Xorg.0.log.old
boot.log.5             kern.log.1              Xorg.1.log
boot.log.6             kern.log.2.gz           Xorg.1.log.old
boot.log.7             kern.log.3.gz

The output shows also directory mysql. This directory contains by default
single log error.log. Let’s view the content of file error.log with cat:

cat /var/log/mysql/error.log

You’ll see the program’s output appear on the screen:

Output
2021-04-28T09:36:19.040254Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.23-0ubuntu0.20.04.1) initializing of server in progress as process 62373
2021-04-28T09:36:19.046865Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2021-04-28T09:36:20.482915Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2021-04-28T09:36:23.709432Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
2021-04-28T09:36:28.971810Z 6 [System] [MY-013172] [Server] Received SHUTDOWN from user boot. Shutting down mysqld (Version: 8.0.23-0ubuntu0.20.04.1).
2021-04-28T09:36:33.851492Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.23-0ubuntu0.20.04.1) starting as process 62437
2021-04-28T09:36:33.870257Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2021-04-28T09:36:34.114770Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2021-04-28T09:36:34.222753Z 0 [ERROR] [MY-011292] [Server] Plugin mysqlx reported: 'Preparation of I/O interfaces failed, X Protocol won't be accessible'
2021-04-28T09:36:34.222924Z 0 [ERROR] [MY-011300] [Server] Plugin mysqlx reported: 'Setup of socket: '/var/run/mysqld/mysqlx.sock' failed, can't create lock file /var/run/mysqld/mysqlx.sock.lock'
2021-04-28T09:36:34.354295Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2021-04-28T09:36:34.354479Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
...

The output shows that the file stores plain text records about the mysqld
server initialisation, and running.

Step 2 — Viewing General Query Logs

The server writes records about each client event during connection to the
general query log. Basically, it keeps the information about all SQL statements
that happens. This log is useful when the administrators want to know what
clients exactly execute.

Connecting to Server and Checking General Query Log Status

First of all, let’s check the status of the general query log because this
logging feature can be turned off.

You can connect to MySQL server as a root client:

You will be redirected to MySQL command-line.

Now, you can view system variables related to the general query log by executing
command show variables:

mysql> show variables like '%general%';

The clause specifies a pattern that should match the variable. In our case, the
pattern '%general%' specifies to show variables that contain the string
general. You’ll see the program’s output appear on the screen:

Output
+------------------+-----------------------------+
| Variable_name    | Value                       |
+------------------+-----------------------------+
| general_log      | ON                          |
| general_log_file | /var/lib/mysql/alice.log    |
+------------------+-----------------------------+
2 rows in set (0.01 sec)

The output shows two variables:

  • general_log: the variable holds value ON (general log enable), or OFF
    (general log disabled).
  • general_log_file: the variable defines where is the log stored in the file
    system.

As you can see, the general query log is by default enabled. We can disconnect
from the server by executing the exit command:

You will be redirected back to the terminal.

Viewing General Query Log

Now, you can view the content of this log with a cat (the sudo is required
because this file is maintained by the system):

$ sudo cat /var/lib/mysql/alice.log

You’ll see the program’s output appear on the screen:

Output
/usr/sbin/mysqld, Version: 8.0.23-0ubuntu0.20.04.1 ((Ubuntu)). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
2021-04-28T10:47:28.713271Z    10 Connect   root@localhost on  using Socket
2021-04-28T10:47:28.713625Z    10 Query select @@version_comment limit 1
2021-04-28T10:53:50.778598Z    10 Query show variables like '%general%'
2021-04-28T13:35:41.944309Z    10 Quit

The output shows all statement executed on the server. You can see the time
stamp and the specific command that was executed. There is also the executed
command show variables like '%general%'.

Step 3 — Listing Binary Logs

The binary log contains events that manipulated the database. If you want to
recover the database, you need a backup and a binary log relevant to this
backup. There are multiple binary logs because they are versioned.

By default, the binary logs are enabled. You can check where are they stored.
Let’s connect to the MySQL server as a root client:

You will be redirected to MySQL prompt.

Now, you can check the binary logs status by executing show binary logs:

The command will list the binary log files on the server:

Output
+---------------+-----------+-----------+
| Log_name      | File_size | Encrypted |
+---------------+-----------+-----------+
| binlog.000001 |       179 | No        |
| binlog.000002 |       403 | No        |
| binlog.000003 |       770 | No        |
| binlog.000004 |       179 | No        |
| binlog.000005 |       403 | No        |
| binlog.000006 |       892 | No        |
+---------------+-----------+-----------+
6 rows in set (0.00 sec)

The output shows all binary logs. Now, we can find out where are this logs
stored.

We can show logs location by executing command show variables:

mysql> show variables like '%log_bin%';

We already use this show clause in the previous step. This time, the clause
shows variables that contain the string log_bin. You’ll see the program’s
output appear on the screen:

Output
+---------------------------------+-----------------------------+
| Variable_name                   | Value                       |
+---------------------------------+-----------------------------+
| log_bin                         | ON                          |
| log_bin_basename                | /var/lib/mysql/binlog       |
| log_bin_index                   | /var/lib/mysql/binlog.index |
| log_bin_trust_function_creators | OFF                         |
| log_bin_use_v1_row_events       | OFF                         |
| sql_log_bin                     | ON                          |
+---------------------------------+-----------------------------+
6 rows in set (0.00 sec)

The output shows that the binary logs are stored in directory /var/lib/mysql,
and they are labelled as binlog.index (for example binlog.000001).

We can disconnect from the server by executing the exit command:

You will be redirected back to the terminal.

Now, let’s list the directory /var/lib/mysql but only as a root because it is
owned and maintained by the system:

You’ll see the program’s output appear on the screen:

Output
auto.cnf         ca.pem                 ib_logfile0    private_key.pem
binlog.000001    client-cert.pem      ib_logfile1      public_key.pem
binlog.000002    client-key.pem       ibtmp1             server-cert.pem
binlog.000003    debian-5.7.flag      '#innodb_temp' server-key.pem
binlog.000004    EXAMPLE_DB           alice.log      sys
binlog.000005    '#ib_16384_0.dblwr'  alice.pid      undo_001
binlog.000006    '#ib_16384_1.dblwr'  mysql            undo_002
binlog.index     ib_buffer_pool       mysql.ibd
ca-key.pem     ibdata1              performance_schema

The output shows that the directory /var/lib/mysql contains the binary log
files.

Step 4 — Configuring Slow Query Log

MySQL allows to log queries, which took too much time. This mechanism is called
a slow query log.

Enabling Slow Query Logging

By default, the slow query log is disabled. You can enable it by editing MySQL
configuration file /etc/mysql/mysql.conf.d/mysqld.cnf (sudo required):

$ sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

The file contains following lines that holds configuration variables (by default
commented out):

...
# Here you can see queries with especially long duration
# slow_query_log          = 1
# slow_query_log_file     = /var/log/mysql/mysql-slow.log
# long_query_time = 10
...

These three lines holds following three configuration variables:

  • slow_query_log: the slow query logging is disable (value 0) or enabled
    (value 1).
  • slow_query_log_file: the slow query log is stored in the file
    /var/log/mysql/mysql-slow.log. You can specify your own file.
  • long_query_time: by default, the slow query logs record each SQL query that
    takes more than 10 seconds. You can change this minimal time interval to
    another value. The value can be specified as a floating-point number where the
    value 1.0 refers to 1 second.

You can enable slow query log by uncommenting this three lines. Also, you can
set your own long_query_time value:

...
# Here you can see queries with especially long duration
slow_query_log          = 1
slow_query_log_file     = /var/log/mysql/mysql-slow.log
long_query_time = 5
...

In our example, we change the default long_query_time value to 5 seconds. Now,
you can save the file.

If you want immediately apply the new configuration rules then you must restart
the MySQL server with systemctl (sudo required):

$ sudo systemctl restart mysql.service

Now, the MySQL server enables slow query log.

Checking Slow Query Log Status

You can check that the log is enabled if you login into the MySQL server as a
root client:

You will be redirected to MySQL prompt.

Let’s check the slow query log status by executing command show variables:

mysql> show variables like '%slow_query_log%';

Once again, we use the show clause. This time, the clause shows variables that
contain the string slow_query_log. You’ll see the program’s output appear on
the screen:

Output
+---------------------+----------------------------------+
| Variable_name       | Value                            |
+---------------------+----------------------------------+
| slow_query_log      | ON                               |
| slow_query_log_file | /var/log/mysql/mysql-slow.log   |
+---------------------+----------------------------------+
2 rows in set (0.00 sec)

The output shows that the slow query log is enabled (the variable
slow_query_log holds the value ON). The log is stored in the file
/var/log/mysql/mysql-slow.log. You can see that it is the same file as the
file specified in the configuration script.

Let’s view actual slow query time interval by executing the command
show variables:

mysql> show variables like '%long_query_time%';

You’ll see the program’s output appear on the screen:

Output
+-----------------+-----------+
| Variable_name   | Value     |
+-----------------+-----------+
| long_query_time |  5.000000 |
+-----------------+-----------+
1 row in set (0.00 sec)

The output shows that the variable long_query_time holds the value 5 seconds
(as we define in the configuration script).

Viewing Slow Query Log

At last, we can check that the MySQL records slow queries to the new log. You
can execute the following select query that takes 6 seconds:

The select will wait 6 seconds and then return 0:

Output
+----------+
| sleep(6) |
+----------+
|        0 |
+----------+
1 row in set (6.01 sec)

The output shows that this query takes 6 seconds. As a result, it should be
recorded in a slow query log.

We can disconnect from the server by executing the exit command:

You will be redirected back to the terminal.

At last, we can print content of the slow query log
/var/log/mysql/mysql-slow.log (the sudo is required because the file is
maintained by system):

$ sudo cat /var/log/mysql/mysql-slow.log

You’ll see the program’s output appear on the screen:

/usr/sbin/mysqld, Version: 8.0.23-0ubuntu0.20.04.1 ((Ubuntu)). started with:
Tcp port: 3306  Unix socket: /var/run/mysqld/mysqld.sock
Time                 Id Command    Argument
# Time: 2021-04-29T06:28:55.445053Z
# User@Host: root[root] @ localhost []  Id:    15
# Query_time: 6.000443  Lock_time: 0.000000 Rows_sent: 1  Rows_examined: 1
SET timestamp=1619677729;
select sleep(6);

You can see that the output shows record about execution query
select sleep(6).

Conclusion

In this tutorial, you configured and viewed different MySQL logs. You installed
the MySQL server and viewed the error log. You connected to the server,
viewed the general query logs and their configuration. You listed binary
logs
. At last, you enabled, configured and viewed a slow query log.

Centralize all your logs into one place.

Analyze, correlate and filter logs with SQL.

Create actionable

dashboards.

Share and comment with built-in collaboration.

Got an article suggestion?
Let us know

Share on Twitter

Share on Facebook

Share via e-mail

Next article

How To Start Logging With PostgreSQL

Learn how to start logging with PostgreSQL and go from basics to best practices in no time.

Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Понравилась статья? Поделить с друзьями:
  • Mysql workbench ошибка 1050
  • Mysql unexpected identifier ошибка
  • Mysql shutdown unexpectedly ошибка
  • Mysql server ошибка установки
  • Mysql no packages found ошибка