假如你是一名 web 开发人员,如果你想调试你的应用或提升其性能的话,那你需要去参考各种日志文件。日志是开始故障排除最好的选择。就著名的 MySql 数据库服务器而言,你需要参考以下日志文件:
错误日志:它包含了服务器运行时(当然也包括服务启动和停止时)所发生的错误信息普通查询日志:这是一个记录 mysqld 在做什么(连接,断开,查询)的通用日志慢查询日志:正如其名,它记录了 “慢” 的查询 SQL 语句本文未涉及到二进制日志。二进制日志要求非常高的服务器硬件配置,而且只是在特定场景下(比如,主从复制,主从安装,某些数据的恢复操作)有用。否则的话,它就是一名实实在在的 “性能杀手”。
通过 MySql 配置启用日志
日志相关参数位于 [mysqld] 部分。
编辑 MySql 配置文件:
nano /etc/mysql/my.cnf
以上是 Debian 下的默认安装目录,其他 Linux 发布版可能不太一样,这个文件中 MySql 服务器的参数如下:
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file = /var/log/mysql/mysql.log
#general_log = 1
#
# Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf.
#
# Here you can see queries with especially long duration
#log_slow_queries = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
# other settings you may need to change.
#server-id = 1
#log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 10
max_binlog_size = 100M
#binlog_do_db = include_database_name
#binlog_ignore_db = include_database_name
MySql 安装默认是不启用所有日志文件的(Windows 平台下的 error 日志除外)。Debian 安装 MySql 默认是将 error 日志发送给 syslog。
error 日志
根据 /etc/mysql/conf.d/mysqld_safe_syslog.cnf 配置,error 日志推送给 syslog:
[mysqld_safe]
syslog
这是推荐的做法。如果你由于某种原因,不想讲 error 日志推给 syslog,将 /etc/mysql/conf.d/mysqld_safe_syslog.cnf 文件中的上述行注掉,或者直接删除掉这个文件,然后在 /etc/mysql/my.cnf 中添加以下行:
[mysqld_safe]
log_error=/var/log/mysql/mysql_error.log
[mysqld]
log_error=/var/log/mysql/mysql_error.log
一般查询日志
要启用一般查询日志,将相关行取消注释(或者添加)即可:
general_log_file = /va
r/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
配置修改后重启 MySql 服务器
以上方法要求服务重启才能生效:
service mysql restart
或者使用 systemd:
systemctl restart mysql.service
运行时启用日志
MySql 5.1 之后我们可以在运行时启用或者禁用日志。
运行时启用日志,登录 MySql 客户端(mysql -u root -p)然后执行:
SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';
运行时禁用日志,登录 Mysql 客户端(mysql -u root -p)后执行:
SET GLOBAL general_log = 'OFF';
SET GLOBAL slow_query_log = 'OFF';