Mysqli error log

В MySQL на данный момент существуют 4 вида журнала (лога) и при достаточно серьёзной работе с базами на 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 инициирует ротацию лога.

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] [email protected] 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   [email protected] 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
# [email protected]: 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 четыре:

  • Error Log — стан­дарт­ный лог оши­бок, кото­рые соби­ра­ют­ся во вре­мя рабо­ты сер­ве­ра (в том чис­ле start и stop);
  • Binary Log — лог всех команд изме­не­ния БД, нужен для репли­ка­ции и бэкапов;
  • General Query Log — основ­ной лог запросов;
  • Slow Query Log — лог мед­лен­ных запросов.

Лог ошибок

Этот жур­нал содер­жит все ошиб­ки, кото­рые про­изо­шли во вре­мя рабо­ты сер­ве­ра, вклю­чая кри­ти­че­ские ошиб­ки, а так­же оста­нов­ки, вклю­че­ния сер­ве­ра и пре­ду­пре­жде­ния (warnings). С него нуж­но начать в слу­чае сбоя систе­мы. По умол­ча­нию все ошиб­ки выво­дят­ся в кон­соль (stderr), так­же мож­но запи­сы­вать ошиб­ки в syslog (по умол­ча­нию в Debian) или отдель­ный лог-файл:

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

Реко­мен­ду­ем дер­жать этот жур­нал вклю­чен­ным для быст­ро­го опре­де­ле­ния оши­бок. А для пони­ма­ния, что зна­чит та или иная ошиб­ка, в MySQL при­сут­ству­ет ути­ли­та perror:

shell> perror 13 64

OS error code  13:  Permission denied

OS error code  64:  Machine is not on the network

Бинарный (он же двоичный) лог

В бинар­ный лог запи­сы­ва­ют­ся все коман­ды изме­не­ния базы дан­ных, при­го­дит­ся для репли­ка­ции и восстановления.

Вклю­ча­ет­ся так:

log_bin                 = /var/log/mysql/mysql-bin.log

expire_logs_days     = 5

max_binlog_size     = 500M

Учти­те, что если вы не соби­ра­е­тесь мас­шта­би­ро­вать систе­му и реа­ли­зо­вы­вать отка­зо­устой­чи­вость, то бинар­ный лог луч­ше не вклю­чать. Он тре­бо­ва­те­лен к ресур­сам и сни­жа­ет про­из­во­ди­тель­ность системы.

Лог запросов

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

general_log_file     = /var/log/mysql/mysql.log

<b>general_log         = 1</b>

Так­же его мож­но включить/отключить во вре­мя рабо­ты сер­ве­ра MySQL:

SET GLOBAL general_log = ON;

SET GLOBAL general_log = OFF;

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

Жур­нал при­го­дит­ся для опре­де­ле­ния мед­лен­ных, то есть неэф­фек­тив­ных запро­сов. Подроб­нее читай­те в этой статье.

Просмотр логов

Для про­смот­ра логов на Debian (Ubuntu) нуж­но выполнить:

# Лог ошибок

tail -f /var/log/syslog

<span class=«comment»> #Лог запро­сов

</span>tail -f /var/log/mysql/mysql.log

<span class=«comment»> # Лог мед­лен­ных запросов

</span>tail -f /var/log/mysql/mysql-slow.log

Ротация логов

Не забы­вай­те сжи­мать (архи­ви­ро­вать, роти­ро­вать) фай­лы логов, что­бы они зани­ма­ли мень­ше места на сер­ве­ре. Для это­го исполь­зуй­те ути­ли­ту logrotate, отре­дак­ти­ро­вав файл кон­фи­гу­ра­ции /etc/logrotate.d/mysql-server:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

# — I put everything in one block and added sharedscripts, so that mysql gets

<span class=«comment»>

#   flush-logs’d only once.

</span>#   Else the binary logs would automatically increase by n times every day.

<span class=«comment»>

# — The error log is obsolete, messages go to syslog now.

</span><b>/var/log/mysql.log /var/log/mysql/mysql.log /var/log/mysql/mysql-slow.log</b> {

        daily

        rotate 7

        missingok

        create 640 mysql adm

        compress

        sharedscripts

        postrotate

                test -x /usr/bin/mysqladmin || exit 0

               <span class=«comment»> # If this fails, check debian.conf!

</span>                MYADMIN=«/usr/bin/mysqladmin —defaults-file=/etc/mysql/debian.cnf»

                if [ -z «`$MYADMIN ping 2&gt;/dev/null`» ]; then

                 <span class=«comment»> # Really no mysqld or rather a missing debian-sys-maint user?

</span>                 <span class=«comment»> # If this occurs and is not an error please report a bug.

</span>                 <span class=«comment»> #if ps cax | grep -q mysqld; then

</span>                  if killall -q -s0 -umysql mysqld; then

                    exit 1

                  fi

                else

                  $MYADMIN flush-logs

                fi

        endscript

}

DDL Log

MySQL так­же ведет лог язы­ка опи­са­ния дан­ных. В него соби­ра­ют­ся дан­ные опе­ра­ций типа DROP_TABLE and ALTER_TABLE. Лог исполь­зу­ет­ся для вос­ста­нов­ле­ния после сбо­ев, кото­рые про­изо­шли во вре­мя выпол­не­ния таких опе­ра­ций. DDL Log — бинар­ный файл, не пред­на­зна­чен­ный для чте­ния поль­зо­ва­те­лем, поэто­му не моди­фи­ци­руй­те и не уда­ляй­те его.

Самое главное

Все­гда вклю­чай­те лог оши­бок, исполь­зуй­те лог запро­сов для про­вер­ки соеди­не­ния при­ло­же­ния с базой дан­ных, про­вер­ки запро­сов и рабо­ты memcached. Лог мед­лен­ных запро­сов при­го­дит­ся для опти­ми­за­ции рабо­ты MySQL.

https://github.com/midnight47/

Всем привет! Заметка будет краткой, так как не хочу открывать лишние вкладки, для того чтобы вспомнить, где и как включать логи. Ниже будет описание о том, какие логи есть (кратко) и как их включить (емко).
Логи в 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

Debugging MySQL in PHP using mysqli

A checklist for potential causes of bugs within your database interaction code in PHP using mysqli


If you have experience using mysqli in PHP, you have probably run into errors with vague or no descriptions at all that take precious time to figure out. For this tutorial we will be going through several errors you may encounter, for examples we’ll be using mysqli object-oriented style but most debugging methods can apply to procedural style as well.

This should be the first step in the process in which you check whether there was a specific error that caused your issue. The error file can usually be found through your local server (if you’re using WAMP or XAMPP) or within your files on your server. This could point out any simple mistakes you’ve made which can be easily corrected, if this doesn’t help then try another method below.

If you need more help accessing your error log, have a look at this

PHP debugging tutorial

.

Sometimes an improperly configured connection to the database can result in the rest of your database interactions not functioning. If this is the case, review the arguments you are passing to the connect function, it is very likely that the given host, user or password is incorrect. To check whether you are properly connected use:

if( $con->connect_error ){      
 echo("connection error"); 
}  
  
if( !$con ){      
 echo("connection error"); 
}      

Sometimes there can be a simple SQL syntax error that you missed within your query, this could be something like a miss-spelled table, columns or keyword. Slowly analyse your query to make sure it is valid.

If you are using statements that you are not entirely familiar with or that you are new to, consider studying more about them or practicing them in your SQL console before attempting to use them in your scripts, many SQL statements have specific requirements that may not be obvious at first.

Sometimes you can inadvertently name tables or columns with the same name as a reserved keyword (eg. naming a column «type»). To avoid this, make sure you familiarise yourself with the MySQL reserved keywords and avoid using these for table or column names entirely.

If you cannot rename the table or column, encapsulate it with accent quotes («) in your SQL statements to make sure MySQL does not see it as a keyword. It is a good practice to surround all your table, column and database names with these quotes anyway.

If you’ve made an error within your SQL that you can’t seem to find, you can call the last error from your connection object, this can then be printed to your log file using error_log(), alternatively you could also echo the error, whichever is more convenient for you.

error_log( $con->error ); 
error_log( mysqli_error( $con ) ); 

In some cases this technique will give you helpful information which you can use to debug an SQL statement.

This is a common error when using prepared statements, this usually points to an error with your SQL syntax or not closing your statements. This error means that $con->prepare($sql) found that your SQL was not valid, and so instead of returning a statement object, it returns false. If you receive this error there is most likely an error in your syntax.

Sometimes it’s a specific section of your SQL query that is the cause of an error. If you query is especially complicated, test the query without certain sections to see if it works, if it does work afterwards, then you will know the specific piece of the query that is the issue. If this does not work, try replacing your query with a simple select statement, if this does not work either, it will rule out your query as the issue.

To rule out your query as the root of the problem, copy it into your MySQL console and run it, if it does so successfully you can usually rule it out as your issue and focus on other pieces of your code.

Sometimes the variables you are using in conjunction with your SQL query can be improperly set, you should check this by echoing each of them or adding them to your error_log.

If you plan on using multiple queries in your script, you must remember to close your statements after executing if you are making use of prepared statements (more on those in

PHP secure database interaction

). If you do not close the used statement and you’ve made use of either parameter binding or result binding, the next time you create a statement, it will not run.

$sql="DELETE FROM testTable WHERE testColumn=1;";      
$stmnt=$con->prepare($sql);      
$stmnt->execute();      
$stmnt->close(); 

Not closing your statements is a common error that can be mistaken for errors within future queries.

When inserting data into a table, you must make sure it matches the data type and length of the the columns you are inserting to. If you are trying to insert a float into an integer column, the database might not insert the data,

this won’t return a relevant error message

which can lead to confusion.

If you are still struggling with an error, feel free to leave comment below.


Понравилась статья? Поделить с друзьями:
  • Mysqli error exception
  • Mysqli error 500
  • Mysqli error 1054
  • Mysqli connect php error
  • Mysqli connect error 2002 no such file or directory