Логи ошибок mysql centos

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&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 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 log File location on Linux Server

mysql error 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 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's user avatar

kenorb

153k86 gold badges674 silver badges738 bronze badges

asked Mar 26, 2011 at 11:21

Arjun's user avatar

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

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

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

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

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

To Enable them just follow below steps:

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

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

To enable error log add following

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

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

To enable general query log add following

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

To enable Slow Query Log add following

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

step3: save the file and restart mysql using following commands

service mysql restart

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

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

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

Click here to visit the blog

Nik's user avatar

Nik

2,8452 gold badges25 silver badges25 bronze badges

answered Apr 2, 2015 at 9:52

loyola's user avatar

loyolaloyola

3,8552 gold badges24 silver badges18 bronze badges

10

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

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

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

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

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

mysql -e "SELECT @@GLOBAL.log_error"

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

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

Note: Hit ControlC when finish

When general log is enabled, try:

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

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

[client]
user=root
password=root

So it’ll be remembered for the next time.

answered Jun 7, 2016 at 17:09

kenorb's user avatar

kenorbkenorb

153k86 gold badges674 silver badges738 bronze badges

2

You have to activate the query logging in mysql.

  1. edit /etc/my.cnf

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

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

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

Nik's user avatar

Nik

2,8452 gold badges25 silver badges25 bronze badges

answered Mar 26, 2011 at 11:28

johnlemon's user avatar

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's user avatar

kenorb

153k86 gold badges674 silver badges738 bronze badges

answered Mar 26, 2011 at 11:29

Mark Nenadov's user avatar

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 :)

Andhi Irawan's user avatar

answered Apr 2, 2014 at 13:04

Line's user avatar

LineLine

1,5193 gold badges18 silver badges41 bronze badges

1

Enter MySQL/MariaDB server command-line tool as root

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

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

  1. Set log file format

SET GLOBAL log_output = ‘FILE’;

  1. Enable the server general log

SET GLOBAL general_log = ‘ON’;

  1. Check your configurations in global configuration variables.

SHOW VARIABLES LIKE «general_log%»;

This will give results as this

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

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

or

less /var/log/mysql/general.log

  1. To disable the general server log

SET GLOBAL general_log = ‘OFF’;

answered Jun 7, 2022 at 12:28

felecian aidan's user avatar

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

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

Community's user avatar

answered Sep 9, 2016 at 14:54

Oussama Romdhane's user avatar

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

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

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

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

Use slightly more compact syntax for the error log:

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

answered Aug 22, 2016 at 11:02

br3w5's user avatar

br3w5br3w5

4,3234 gold badges33 silver badges42 bronze badges

shell> mysqladmin flush-logs


shell> mv host_name.err-old backup-directory

Shaunak D's user avatar

Shaunak D

20.5k10 gold badges45 silver badges79 bronze badges

answered Apr 15, 2015 at 13:27

Test's user avatar

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!

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Логи iis ошибка 500
  • Логан ошибка р0110
  • Логан ошибка неисправность кодированной связи
  • Лог файл ошибок windows 10

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии