Thank you for reading this post, don’t forget to subscribe!
Журналы событий — первый и самый простой инструмент для определения статуса системы и выявления ошибок. Основных логов в 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>/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 Log File Location on a Redhat/CentOS/Fedora Linux Server
On Redhat/CentOS Server mySQL log will be saved in /var/log directory. Check /var/log directory for mySQL log files.
MySQL log file on Redhat/CentOS Server : /var/log/mysqld.log
On some servers mySQL logs might be in a different location. Do the below steps to find out mySQL log file location if you didn’t see the logs in the above default location.
Log into your Linux Server via SSH as root and run the below command to check the mySQL error log file location. The error log and mySQL general log might be already set in the my.cnf file. Run the command “cat my.cnf” to view the content of mySQL configuration file. Do the below steps if you didn’t see any log file location set in my.cnf file.
root@server [~]# mysqladmin variables | grep log_error
| log_error | /var/lib/mysql/server.err
On the above server mySQL error logs are saved in the file /var/lib/mysql/server.err
Type the below command to check the mySQL general_log_file location.
root@server [~]# mysqladmin variables | grep general_log_file
| general_log_file | /var/lib/mysql/server.log
mySQL log File location on Linux Server
mysql error log file location on linux Server
On my server mySQL error log files and general log file are saved in the above location.
Run the below command to check the slow query log location on Redhat Server.
root@server [~]# mysqladmin variables | grep slow_query_log_file
| slow_query_log_file | /var/lib/mysql/server-slow.log
MySQL slow query log file Location Redhat CentOS Server
В 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 инициирует ротацию лога.
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
153k86 gold badges674 silver badges738 bronze badges
asked Mar 26, 2011 at 11:21
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
2,8452 gold badges25 silver badges25 bronze badges
answered Apr 2, 2015 at 9:52
loyolaloyola
3,8552 gold badges24 silver badges18 bronze badges
10
The MySQL logs are determined by the global variables such as:
log_errorfor the error message log;general_log_filefor the general query log file (if enabled bygeneral_log);slow_query_log_filefor the slow query log file (if enabled byslow_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 Control—C 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
kenorbkenorb
153k86 gold badges674 silver badges738 bronze badges
2
You have to activate the query logging in mysql.
-
edit /etc/my.cnf
[mysqld] log=/tmp/mysql.log
-
restart the computer or the mysqld service
service mysqld restart
-
open phpmyadmin/any application that uses mysql/mysql console and run a query
-
cat /tmp/mysql.log( you should see the query )
Nik
2,8452 gold badges25 silver badges25 bronze badges
answered Mar 26, 2011 at 11:28
johnlemonjohnlemon
20.7k41 gold badges119 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
153k86 gold badges674 silver badges738 bronze badges
answered Mar 26, 2011 at 11:29
Mark NenadovMark Nenadov
6,3715 gold badges24 silver badges31 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 
answered Apr 2, 2014 at 13:04
LineLine
1,5193 gold badges18 silver badges41 bronze badges
1
Enter MySQL/MariaDB server command-line tool as root
- 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’;
- Set log file format
SET GLOBAL log_output = ‘FILE’;
- Enable the server general log
SET GLOBAL general_log = ‘ON’;
- Check your configurations in global configuration variables.
SHOW VARIABLES LIKE «general_log%»;
- Enter
exitto leave MySQL command-line and Tail your queries by
tail -f /var/log/mysql/general.log
or
less /var/log/mysql/general.log
- To disable the general server log
SET GLOBAL general_log = ‘OFF’;
answered Jun 7, 2022 at 12:28
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
answered Sep 9, 2016 at 14:54
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
br3w5br3w5
4,3234 gold badges33 silver badges42 bronze badges
shell> mysqladmin flush-logs
shell> mv host_name.err-old backup-directory
Shaunak D
20.5k10 gold badges45 silver badges79 bronze badges
answered Apr 15, 2015 at 13:27
1
I am having a heck of a time getting this web server to log MySQL errors for me. I just started having issues with MySQL crashing every night and having to restart the service. I am running MySQL on CentOS release 7.6.1810 and the MySQL version is 15.1 (distrib 10.1.37-MariaDB).
I am trying to pinpoint the cause but I am unable to get the log files to generate.
If I go to:
/etc/my.cnf
then edit it in nano it does not have the [mysql] line in the file.
This is where you would add in the general_log stuff.
However, in /etc/my.cnf.d/ I do have a mysql-clients.cnf and a server.cnf which do show the [mysql] line in the file to add in the logs.
If I add the line in manually to my.cnf when I stop the service I cannot restart it.
I get an error:
Job for mariadb.service failed because the control process exited with error code.
The same thing happens if I add the code for the log files in the server.cnf.
If I add the code in on the mysql-clients.cnf I can stop and start the server with no issues, but nothing is being written to any of the files.
I also created the files and gave them 777 permissions and chown to mysql:mysql.
Does anyone have any idea on what I can do to get this logging?
The following lines are what I have been trying to add:
[mysqld_safe]
log_error=/var/log/mysql/mysql_error.log
[mysqld]
log_error=/var/log/mysql/mysql_error.log
general_log_file = /var/log/mysql/mysql.log
general_log = 1
log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes
Thank you for any and all help!



