How can I enable MySQL slow query log on my server

2020-02-07 17:35发布

How do I enable slow query log on my server? I have enabled it on my local host by adding log-slow-queries =[path] in my.ini file, but don't know how to add this on my server. My server is Linux-based and has PHP version 5.2.16.

标签: mysql
3条回答
倾城 Initia
2楼-- · 2020-02-07 18:09

Enabling slow query log has nothing to do with PHP version. You have to enable it in the MySQL server. You can enable in two ways

  1. In runtime
  2. During the server start

If your server is above 5.1.6 you can set the slow query log in the runtime itself. For which you have to execute this queries.

set global log_slow_queries = 1;
set global slow_query_log_file = <some file name>;

Or alternatively you can set the this options in the my.cnf/my.ini option files

log_slow_queries = 1; 
slow_query_log_file = <some file name>;

Where the option file is changed, the MySQL server need to be restarted.

Location of the mysql option file can be found here http://dev.mysql.com/doc/refman/4.1/en/mysql-config-wizard-file-location.html

FYI : log_slow_queries was removed in MySQL 5.6.1 and slow_query_log is used instead. http://dev.mysql.com/doc/refman/5.6/en/server-options.html#option_mysqld_log-slow-queries

But for performance you can set the log output (option log_output) to TABLE. Also you can have a look other slow query log options like long_query_time, log-queries-not-using-indexes

查看更多
▲ chillily
3楼-- · 2020-02-07 18:09

First (as root:)

mkdir /var/log/mysql
touch /var/log/mysql/log-slow-queries.log
chown mysql:mysql -R /var/log/mysql

Then under [mysqld] in /etc/my.conf (or wherever your configuration file is:)

slow_query_log = 1
log-queries-not-using-indexes
long_query_time=1
log-slow-queries=/var/log/mysql/log-slow-queries.log

Next:

service mysql restart

Finally:

mysql
mysql> SELECT SLEEP(10);
mysql> quit

Verification:

cat /var/log/mysql/log-slow-queries.log

/usr/sbin/mysqld, Version: 5.5.42-cll (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: (null)
Time                 Id Command    Argument
# Time: 150727  0:05:17
# User@Host: root[root] @ localhost []
# Query_time: 10.000215  Lock_time: 0.000000 Rows_sent: 1  Rows_examined: 0
SET timestamp=1437973517;
select sleep(10);
查看更多
三岁会撩人
4楼-- · 2020-02-07 18:11

You can set it temporarily, by running the following commands:

set global slow_query_log = 1;
set global slow_query_log_file = '/var/log/mysql-slow.log';

but your changes will be undone when mysql is restarted.

You can set it permanently, by adding the following to your my.cnf file:

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

The location of my.cnf varies by OS, but is often found in /etc/my.cnf, or /etc/mysql/my.cnf:

After saving your changes, you will need to restart MySql. This can vary by OS, but here are some common examples:

sudo /etc/init.d/mysqld restart

and

sudo service mysqld restart
查看更多
登录 后发表回答