Как посмотреть логи mysql в windows

I've read that Mysql server creates a log file where it keeps a record of all activities - like when and what queries execute. Can anybody tell me where it exists in my system? How can I read it?

I’ve read that Mysql server creates a log file where it keeps a record of all activities — like when and what queries execute.

Can anybody tell me where it exists in my system? How can I read it?

Basically, I need to back up the database with different input [backup between two dates] so I think I need to use log file here, that’s why I want to do it…

I think this log must be secured somehow because sensitive information such as usernames and password may be logged [if any query require this]; so may it be secured, not easily able to be seen?

I have root access to the system, how can I see the log?

When I try to open /var/log/mysql.log it is empty.

This is my config file:

[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock

[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
log = /var/log/mysql/mysql.log 
binlog-do-db=zero



user        = mysql
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
skip-external-locking

bind-address        = 127.0.0.1
#
# * Fine Tuning
#
key_buffer      = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8

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

kenorb's user avatar

kenorb

149k80 gold badges667 silver badges722 bronze badges

asked Mar 26, 2011 at 11:21

Arjun's user avatar

Here is a simple way to enable them. In mysql we need to see often 3 logs which are mostly needed during any project development.

  • The Error Log. It contains information about errors that occur while
    the server is running (also server start and stop)

  • The General Query Log. This is a general record of what mysqld is
    doing (connect, disconnect, queries)

  • The Slow Query Log. Ιt consists of «slow» SQL statements (as
    indicated by its name).

By default no log files are enabled in MYSQL. All errors will be shown in the syslog (/var/log/syslog).

To Enable them just follow below steps:

step1: Go to this file (/etc/mysql/conf.d/mysqld_safe_syslog.cnf) and remove or comment those line.

step2: Go to mysql conf file (/etc/mysql/my.cnf) and add following lines

To enable error log add following

[mysqld_safe]
log_error=/var/log/mysql/mysql_error.log

[mysqld]
log_error=/var/log/mysql/mysql_error.log

To enable general query log add following

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

To enable Slow Query Log add following

log_slow_queries       = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes

step3: save the file and restart mysql using following commands

service mysql restart

To enable logs at runtime, login to mysql client (mysql -u root -p) and give:

SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';

Finally one thing I would like to mention here is I read this from a blog. Thanks. It works for me.

Click here to visit the blog

Nik's user avatar

Nik

2,7252 gold badges23 silver badges25 bronze badges

answered Apr 2, 2015 at 9:52

loyola's user avatar

loyolaloyola

3,7852 gold badges24 silver badges18 bronze badges

10

The MySQL logs are determined by the global variables such as:

  • log_error for the error message log;
  • general_log_file for the general query log file (if enabled by general_log);
  • slow_query_log_file for the slow query log file (if enabled by slow_query_log);

To see the settings and their location, run this shell command:

mysql -se "SHOW VARIABLES" | grep -e log_error -e general_log -e slow_query_log

To print the value of error log, run this command in the terminal:

mysql -e "SELECT @@GLOBAL.log_error"

To read content of the error log file in real time, run:

sudo tail -f $(mysql -Nse "SELECT @@GLOBAL.log_error")

Note: Hit ControlC when finish

When general log is enabled, try:

sudo tail -f $(mysql -Nse "SELECT CONCAT(@@datadir, @@general_log_file)")

To use mysql with the password access, add -p or -pMYPASS parameter. To to keep it remembered, you can configure it in your ~/.my.cnf, e.g.

[client]
user=root
password=root

So it’ll be remembered for the next time.

answered Jun 7, 2016 at 17:09

kenorb's user avatar

kenorbkenorb

149k80 gold badges667 silver badges722 bronze badges

2

You have to activate the query logging in mysql.

  1. edit /etc/my.cnf

    [mysqld]
    log=/tmp/mysql.log
    
  2. restart the computer or the mysqld service

    service mysqld restart
    
  3. open phpmyadmin/any application that uses mysql/mysql console and run a query

  4. cat /tmp/mysql.log ( you should see the query )

Nik's user avatar

Nik

2,7252 gold badges23 silver badges25 bronze badges

answered Mar 26, 2011 at 11:28

johnlemon's user avatar

johnlemonjohnlemon

20.5k40 gold badges118 silver badges178 bronze badges

2

From the MySQL reference manual:

By default, all log files are created in the data directory.

Check /var/lib/mysql folder.

kenorb's user avatar

kenorb

149k80 gold badges667 silver badges722 bronze badges

answered Mar 26, 2011 at 11:29

Mark Nenadov's user avatar

Mark NenadovMark Nenadov

6,2515 gold badges22 silver badges29 bronze badges

5

In my (I have LAMP installed) /etc/mysql/my.cnf file I found following, commented lines in [mysqld] section:

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

I had to open this file as superuser, with terminal:

sudo geany /etc/mysql/my.cnf

(I prefer to use Geany instead of gedit or VI, it doesn’t matter)

I just uncommented them & save the file then restart MySQL with

sudo service MySQL restart

Run several queries, open the above file (/var/log/mysql/mysql.log) and the log was there :)

Andhi Irawan's user avatar

answered Apr 2, 2014 at 13:04

Line's user avatar

LineLine

1,4913 gold badges18 silver badges41 bronze badges

1

Enter MySQL/MariaDB server command-line tool as root

  1. Set file path (you can replace general.log with the file name of your choice).

SET GLOBAL general_log_file=’/var/log/mysql/general.log’;

  1. Set log file format

SET GLOBAL log_output = ‘FILE’;

  1. Enable the server general log

SET GLOBAL general_log = ‘ON’;

  1. Check your configurations in global configuration variables.

SHOW VARIABLES LIKE «general_log%»;

This will give results as this

  1. Enter exit to leave MySQL command-line and Tail your queries by

tail -f /var/log/mysql/general.log

or

less /var/log/mysql/general.log

  1. To disable the general server log

SET GLOBAL general_log = ‘OFF’;

answered Jun 7, 2022 at 12:28

felecian aidan's user avatar

To complement loyola’s answer it is worth mentioning that as of MySQL 5.1 log_slow_queries is deprecated and is replaced with slow-query-log

Using log_slow_queries will cause your service mysql restart or service mysql start to fail

Community's user avatar

answered Sep 9, 2016 at 14:54

Oussama Romdhane's user avatar

In addition to the answers above you can pass in command line parameters to the mysqld process for logging options instead of manually editing your conf file. For example, to enable general logging and specifiy a file:

mysqld --general-log --general-log-file=/var/log/mysql.general.log

Confirming other answers above, mysqld --help --verbose gives you the values from the conf file (so running with command line options general-log is FALSE); whereas mysql -se "SHOW VARIABLES" | grep -e log_error -e general_log gives:

general_log     ON
general_log_file        /var/log/mysql.general.log

Use slightly more compact syntax for the error log:

mysqld --general-log --general-log-file=/var/log/mysql.general.log --log-error=/var/log/mysql.error.log

answered Aug 22, 2016 at 11:02

br3w5's user avatar

br3w5br3w5

4,2934 gold badges32 silver badges42 bronze badges

shell> mysqladmin flush-logs


shell> mv host_name.err-old backup-directory

Shaunak D's user avatar

Shaunak D

20.5k10 gold badges45 silver badges78 bronze badges

answered Apr 15, 2015 at 13:27

Test's user avatar

1

В 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 инициирует ротацию лога.

Содержание

  1. Журналы (logs) в MySQL
  2. Бинарный лог
  3. Лог ошибок
  4. Лог медленных запросов
  5. Лог запросов
  6. Лог репликаций
  7. MySQL Log File Location
  8. MySQL Logs
  9. The Question of How and Where with MySQL Log Files
  10. Windows
  11. Platform-Specific UNIX/Linux
  12. Generic UNIX/Linux
  13. The MySQL Error Log
  14. The General and Slow Query Logs
  15. Binary, Relay, and DDL Logs
  16. Simplifying MySQL Log File location with Sumo Logic
  17. Complete visibility for DevSecOps

Журналы (logs) в MySQL

В 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 Log File Location

Logs are valuable. Logs generated by a major backend resource that provides clients with access to crucial data are more than just valuable; knowing where they are and being able to manage and understand the information that they contain can mean the difference between smooth, secure operation and degraded performance or even catastrophic failure for your application.

MySQL Server produces a handful of basic logs. We’ll look at which ones are important (and why), where they are, and what you can do to get the most out of them.

MySQL Logs

The three most important logs in terms of day-to-day IT operations are the error log, the slow query log, and (to a lesser degree) the general query log. Their default format is text, and they are useful for detecting and diagnosing functional problems and security issues, for improving performance, and for tracing the history of server operations and client access to the server.

The binary, relay, and DDL logs are all binary in format, and they are designed for use primarily by MySQL itself, specifically for tasks such as server replication and data recovery.

The Question of How and Where with MySQL Log Files

First, let’s take a quick look at how and under what circumstances the various MySQL distributions set default log file locations.

There are three basic types of MySQL distribution: Windows, platform-specific UNIX/Linux, and generic UNIX/Linux. In general, the platform-specific distributions have default settings for placing and enabling logs, while the generic UNIX/Linux distributions assume that logs will be managed via manual settings.

Windows

Official MySQL Windows distributions use an MSI installer with user-selectable options at various stages of the installation. The Logging Options page displays the log enabling and location defaults and also allows you to make adjustments as required.

The error, slow query, and binary logs are enabled by default, but the general query log is not enabled. The default location for each of the logs is the MySQL Data directory (C:ProgramDataMySQLMySQL Server [version number]Data), and the default log names are based on the computer’s device name.

You can manually enable/disable the general query, slow query, and binary logs via the installer GUI, but not the error log. You can also manually set the names and paths for each of the logs.

After installation, the log settings are managed via the user-editable C:ProgramDataMySQLMySQL Server [version number]my.ini file. These settings include log names and paths as well as enable/disable switches.

For more information on collecting Microsoft MySQL logs, see our dedicated page to collecting and understanding MySQL Logs on windows.

Platform-Specific UNIX/Linux

The official distributions for individual UNIX/Linux platforms are typically script-based, with little or no interactive configuration during installation. Some installation packages (including Yum and APT) create the error log in /var/log/ or var/log/mysql/ with a name like error.log or mysqld.log. The data directory will typically be /var/lib/mysql/ or something similar, and it will serve as the default destination for any logs that are enabled without an alternate path.

The log settings are managed via a user-editable configuration file such as /etc/mysql/mysql.conf.d/mysqld.cnf. These settings include log names and paths as well as enable/disable switches. Startup and shutdown are typically managed by mysqld_safe (or with some distributions, systemd), which should find and apply log configuration options.

Generic UNIX/Linux

Generic installation is largely manual. During the installation process, you can enable and configure logs via the command line, by running scripts, or by editing the appropriate configuration file. The MySQL online reference manual (https://dev.mysql.com/doc/refman/5.7/en/server-logs.html) covers these options in detail.

The MySQL Error Log

The error log includes error messages, warnings, and notes generated during server operations as well as during the startup and shutdown phases; it also records startup and shutdown times.

The basic error log format is:

Error logging is always enabled, and the available options allow you to set the destination, verbosity level, and time zone.

Possible error log destinations are a file or the console. On Windows, if no destination option is specified, the error log is written to host_name.err (where host_name is the host system name) in the data directory. On UNIX/Linux systems, the default destination when no option is specified is the console.

For both UNIX/Linux and Windows-based MySQL installations, the —log-error option by itself (with no file name or path) sends the error log to host_name.err in the Data directory. If you specify the name and path (i.e., —log-error=»G:/TMP/mysql_logs/mysql_error.err» or —log-error=/var/log/mysql/error.log), the error log will be written to the specified file. In order to send the error log to the console on Windows, you must use the —console option; it overrides the —log-error option if both are present.

For more information regarding error logs and collecting them, see our page on Collecting logs in MySQL.

The General and Slow Query Logs

The general query and slow query logs both record user queries using a similar format: Time, ID, Command, and Argument (where Argument includes both the SQL commands and the data making up the query).

The general query log, however, records all client SQL statements along with connect and disconnect times, while the slow query log only records queries that take longer than the time specified by the long-query-time system variable. The slow query log also includes a set of fields containing the execution time, lock time, rows sent, and rows examined for each logged query.

A typical general query log entry might look like this:

The slow query log entry for the same event might look like this:

The slow query log allows you to identify queries that require an unusually long time to execute; it may also be of use in uncovering system or database issues that result in slow execution. The general query log allows you to track all client SQL statements, which can be useful both for tracing errors and for identifying potential security problems.

The query logs tend to accumulate data rapidly, which may impact system performance in addition to taking up disk space. The general query log in particular can grow very quickly; both it and the slow query log are disabled by default in most installation packages. (The Windows MySQL installer, however, is an exception, as described above.)

The general query and slow query logs are enabled separately, using the —general-log and —slow-query-log options. The default destination is the data directory, with (host name].log and [host name]-slow.log as the file names. To set the log names and paths, use the —general-log-file and —slow-log-file options.

The format of both logs is controlled by a single option, —log-output, which takes the following values: FILE, TABLE, or NONE. FILE is the default value. TABLE stores both logs as tables, which can be read and managed via SQL queries. Both FILE and TABLE can be used together, separated by commas. NONE disables the output of both logs; if it is present, it overrides the other values.

Binary, Relay, and DDL Logs

The binary and relay logs are necessary for server replication, and the DDL log is used by the system to manage metadata during mysqld operation. These logs are generally of limited diagnostic use, although you may need to access binary and relay logs using the mysqlbinlog utility as part of the data recovery process.

Simplifying MySQL Log File location with Sumo Logic

The truth is that even with a relatively small number of server logs, MySQL can generate a lot of log data. At the same time, elements of that data may be important in terms of error-tracking, performance, and security. What’s the best way to organize and sort through MySQL server log data in order to find the things that you need to know?

The Sumo Logic App for MYSQL automatically picks out key metrics and data items from the error and slow query logs and presents them in easy-to-read dashboards. Sumo Logic makes it easy to identify performance issues, unusual behavior and activity patterns, and critical errors. You can check system health, replication status, and server performance at a glance, drilling down to detailed real-time information on slow queries (including origin by individual host, IP, and user), failed logins (by user, host, and location), and replication and server problems.

Don’t spend hours digging through log files — let Sumo Logic do the work for you so that you have time to get down to the business of serving your customers!

Complete visibility for DevSecOps

Reduce downtime and move from reactive to proactive monitoring.

Источник

MySQL Log File

Introduction of MySQL Log File

MySQL log file consists of records of actions that has been performed. MySQL server generates log files that are generated based on the actions performed. The log files are of different types: – error logs, ISAM log, general query log, update log, binary log, and slow query log.

  • Error log File: It consists of all the records that has been encountered while running, starting or stopping mysql.
  • ISAM Log File: It records all the changes that has been done to the ISAM tables.Used only for ISAM code debugging.
  • General Query Log File: Contains information regarding the connections established and executed queries.
  • Update Log File: Consists of information on all the changes that have been performed on data.
  • Binary Log File: Which consists of all the modification that happened in the database
  • Slow Query Log File: Stores all the details of the queries that took more than the “long_query_time” to execute.

Syntax of MySQL Log File

To check log location and settings the error log file in the shell:

mysql -se "SHOW VARIABLES" | grep -e log_error

To check log location and settings the general log file in the shell:

mysql -se "SHOW VARIABLES" | grep-e general_log

To check log location and settings the slow query log file in the shell:

mysql -se "SHOW VARIABLES" | grep -e slow_query_log

How does MySQL Log File Works?

Now let us see the error log that records the information about the errors encountered while running, starting or stopping mysqld. In windows, we have the path called “C:ProgramDataMySQLMySQL Server 8.0Data” which consists of the error log as mentioned in the below screenshot. The type of the error log file is “err”. Below we have highlighted the same.

MySQL Log File-1.1

1. Error Log File

We can see the details of the error log file in the “config” file (my.ini) from the path

“C:ProgramDataMySQLMySQL Server 8.0”.
# Error Logging.
log-error="LAPTOP-78SCO0PP.err"

MySQL Log File-1.2

2. General Log File

Contains information regarding the connections established and executed queries.We can see the details of the general log file in the “config” file (my.ini) from the path “C:ProgramDataMySQLMySQL Server 8.0”.

# General and Slow logging.
log-output=FILE
general-log=0
general_log_file="LAPTOP-78SCO0PP.log"

MySQL Log File-1.3

Here the “general-log” =0 which means that the general log is not enabled. To enable we need to set the value to “general-log” =1.

3. Binary Log File

Show BINARY LOGS

Output:

Log_name file_size Encrypted
LAPTOP-78SCO0PP-bin.000001 179 No
LAPTOP-78SCO0PP-bin.000002 2129912 No

mysqlbinlog log-file | mysql -h server_name

4. ISAM Log File

myisamlog processes contain the information of a MyISAM log file. In order to create the ISAM log file, we start the server with a –log-isam=log_file option. We just need to invoke myisamlog as below:

myisamlog [options] [file_name [tbl_name] …]
Options can be of –c, -f, -F, -i, -o etc

5. Update Log File

The update log is replaced by the binary log. When the server is started, we mention the option with a file name as “–log-update[=file_name]” , mysqld writes a log file containing all SQL commands that update data like UPDATE or DELETE. It skips the UPDATE statements if the column value is already existing.

6. Slow Query Log File

Stores all the details of the queries that took more than the “long_query_time” to execute. Below is the query that shows the longest query executed.

We can see the details of the general log file in the “config” file (my.ini) from the path “C:ProgramDataMySQLMySQL Server 8.0”.

# Slow logging.
slow-query-log=1
slow_query_log_file="LAPTOP-78SCO0PP-slow.log"
long_query_time=10

Output-1.4

7. Error Log File

Once we open the “error” log file we get the below data information: –

  • InnoDB initialization has started.
  • InnoDB initialization has ended.
  • X Plugin ready for connections. Bind-address: ‘::’ port: 33060
  • CA certificate ca.pem is self signed.
Timestamp Thread Type Details
2020-05-31T09:34:06 0 [Warning] [MY-000081] [Server] option ‘read_buffer_size’: unsigned value 5120 adjusted to 8192.
2020-05-31T09:34:06 0 [Warning] [MY-010915] [Server] ‘NO_ZERO_DATE’, ‘NO_ZERO_IN_DATE’, and ‘ERROR_FOR_DIVISION_BY_ZERO’ sql modes should be used with strict mode. They will be merged with strict mode in a future release.
2020-05-31T09:34:06 0 [System] [MY-010116] [Server] C:Program FilesMySQLMySQL Server 8.0binmysqld.exe (mysqld 8.0.20) starting as process 16316
2020-05-31T09:34:06 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2020-05-31T09:34:13 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2020-05-31T09:34:14 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: ‘::’ port: 33060
2020-05-31T09:34:17 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2020-05-31T09:34:17 0 [System] [MY-010931] [Server] C:Program FilesMySQLMySQL Server 8.0binmysqld.exe: ready for connections. Version: ‘8.0.20’ socket: ” port: 3306 MySQL Community Server – GPL.
2020-06-13T10:22:35 0 [System] [MY-013105] [Server] C:Program FilesMySQLMySQL Server 8.0binmysqld.exe: Normal shutdown.
2020-06-13T10:23:20 0 [System] [MY-010910] [Server] C:Program FilesMySQLMySQL Server 8.0binmysqld.exe: Shutdown complete (mysqld 8.0.20) MySQL Community Server – GPL.
2020-06-13T10:26:03 0 [Warning] [MY-000081] [Server] option ‘read_buffer_size’: unsigned value 5120 adjusted to 8192.
2020-06-13T10:26:03 0 [Warning] [MY-010915] [Server] ‘NO_ZERO_DATE’, ‘NO_ZERO_IN_DATE’ and ‘ERROR_FOR_DIVISION_BY_ZERO’ sql modes should be used with strict mode. They will be merged with strict mode in a future release.
2020-06-13T10:26:04 0 [System] [MY-010116] [Server] C:Program FilesMySQLMySQL Server 8.0binmysqld.exe (mysqld 8.0.20) starting as process 6292
2020-06-13T10:26:08 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2020-06-13T10:26:18 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2020-06-13T10:26:25 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: ‘::’ port: 33060
2020-06-13T10:26:29 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2020-06-13T10:26:30 0 [System] [MY-010931] [Server] C:Program FilesMySQLMySQL Server 8.0binmysqld.exe: ready for connections. Version: ‘8.0.20’ socket: ” port: 3306 MySQL Community Server – GPL.

Output-1.5

8. Slow Query Log File

We can see the details of the general log file in the “config” file (my.ini) from the path “C:ProgramDataMySQLMySQL Server 8.0”.

Now let us see the slow query log file. Below are the details that we get from our database.

Start Time User@Host Query Time Lock Time Rows Sent Rows Examined Detail
2020-06-06T12:48:49 root[root] @ localhost [::1] Id: 32 11.770594 0.032157 174 960 use sourcedb;
SET timestamp=1591447717;
SELECT * FROM information_schema.`TABLES` T,
information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
LIMIT 0, 1000;

Output-1.6

Recommended Articles

This is a guide to MySQL Log File. Here we also discuss the introduction and how does mysql log file works along with examples and its code implementation. You may also have a look at the following articles to learn more –

  1. MySQL BIN()
  2. MySQL INSTR()
  3. MySQL WHILE LOOP
  4. MySQL Root

Nov 27, 2018 by Robert Gravelle

In software applications, log files keep a record of what actions were performed in the system and perhaps who performed them. Should something unexpected occur, whether it be a security breach, system crash, or just sluggish performance, the log file(s) can be an administrator’s best friend. As it happens, MySQL has several different log files that can help you find out what’s going on inside the MySQL server. Today’s blog is a primer on MySQL logging — a topic that we’ll be referencing later on when we talk about monitoring in Navicat Monitor for MySQL/MariaDB.

Log Types

MySQL can support several log types, but bear in mind that, by default, no logs are enabled except for the error log on Windows. Here’s a list of types:

Log file Description
The error log Problems encountered when starting, running, or stopping mysqld.
The isam log Logs all changes to the ISAM tables. Used only for debugging the ISAM code.
The general query log Established connections and executed queries.
The update log Deprecated: stores all statements that change data.
The binary log Stores all statements that change something. Used also for replication.
The slow log Stores all queries that took more than long_query_time to execute or didn’t use indexes.

Out of these, the most important are the error, general, binary, and slow logs, so we’ll focus on the first two today, and the last two next week.

The error log

Your first resource when troubleshooting server issues is the error log. MySQL server uses the error log to record information relevant to any issue which prevents the server from starting. You’ll find the error log in the data directory specified in your my.ini file. The default data directory location in Windows is «C:Program FilesMySQLMySQL Server 5.7data», or «C:ProgramDataMysql». Note that the «C:ProgramData» directory is hidden by default, so you may need to change your folder options to see the directory and its contents.

Fig.1 — the MySQL Error log in Windows

For other platforms, it may be helpful to refer to the log_error config variable. If you use Navicat to manage your database(s), you can look up system variables using the Server Monitor tool. It’s accessible via the Tools main menu command.

In the Server Monitor, click on the middle «Variables» tab and scroll down to log_error in the list:

Fig.2 — the log_error server variable in the Navicat Server Monitor tool

The General Query Log

As the name implies, the general query log provides a general record of what MySQL is doing. The server writes information to this log when clients connect or disconnect, as well as each SQL statement received from clients. The general query log can be very useful when you suspect an error in a client application and want to know exactly what the client sent to the database.

By default, the general query log is disabled. To enable it, set the general_log variable to 1 (or ON in Navicat). Not assigning any value to general_log also enables it. Setting it back to 0 (or OFF in Navicat) disables the log. To specify a log file name, assign it to the general_log_file variable. To specify that the log outputs to a file, use the log_output system variable to assign the file name. MySQL can also send output to the slow_log tables in the mysql system database. In fact, file output, table output, or both can be selected. We’ll talk about that in greater detail in the next blog.

Fig.3 — the general_log and general_log_file server variables in the Navicat Server Monitor tool

Всем привет! Заметка будет краткой, так как не хочу открывать лишние вкладки, для того чтобы вспомнить, где и как включать логи. Ниже будет описание о том, какие логи есть (кратко) и как их включить (емко).
Логи в 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
  1. Home
  2. Coding
  3. MySQL
  4. Журналы работы сервера MySQL — ошибок, двоичные, общих запросов, медленных запросов

Статья содержит краткое описание журналов работы сервера MySQL — журнал ошибок, общий журнал запросов, журнал медленных запросов, двоичные журналы

Все журналы связанные с работой сервера MySQL по умолчанию находятся в папке data корневой папки MySQL (той паки куда был установлен MySQL).

Представляет файл с расширением .err. В качестве имени файла берется hostname (hostname.err). Содержит информацию  об ошибках в работе, запусках и остановках сервера. Данные хранятся в текстовом виде, поэтому их можно посмотреть любым текстовым редактором.

Общий журнал запросов MySQL

Представляет файл с расширением .log. В качестве имени файла берется hostname (hostname.log). Содержит информацию о подключениях клиентских программ и выполняемых запросах. Для ведения этих журналов сервер должен быть запущен с параметром – log. Данные хранятся в текстовом виде, поэтому их можно посмотреть любым текстовым редактором.

Журнал медленных запросов MySQL

Представляет файл с  именем hostname-show.log.  Содержит информацию об длительных АО времени  SQL-запросах (по умолчанию – более 10 с), служит для обнаружения объектов,  требующих  оптимизации.  Для ведения этих журналов сервер должен быть запущен с параметром – log-slow-queries. Данные хранятся в текстовом виде, поэтому их можно посмотреть любым текстовым редактором.

Двоичные журналы MySQL

Представляет файл с  именем hostname-bin.xxxxxx, где xxxxxx – порядковый номер журнала. Содержат историю изменений данных в базе. Для ведения этих журналов сервер должен быть запущен с параметром – log-bin.  Для  просмотра  двоичных  журналов  необходимо использовать специальную утилиту mysqlbinlog (запускается из командной строки)

mysqlbinlog  hostname-bin.xxxxxx — Выведет содержимое в виде SQL-команд.

mysqlbinlog hostname-bin.xxxxxx filename – Запишет содержимое в виде SQL-команд в файл, который можно посмотреть любым текстовым редактором.

На этом все, всем пока.

Меня два раза спрашивали [члены Парламента]: «Скажите на милость, мистер Бэббидж, что случится, если вы введёте в машину неверные цифры? Cможем ли мы получить правильный ответ?» Я не могу себе даже представить, какая путаница в голове может привести к подобному вопросу. / Charles Babbage /

Понравилась статья? Поделить с друзьями:
  • Как посмотреть лицензию windows в биосе
  • Как посмотреть лицензию windows в bios
  • Как посмотреть лицензию windows 7 на компе
  • Как посмотреть лицензию windows 10 на учетной записи
  • Как посмотреть лицензию windows 10 в реестре