MySQL 常用 ~ 工具、日志。

MySQL 常用 ~ 工具、日志。



mysql。

https://dev.mysql.com/doc/refman/5.7/en/programs-client.html

该 mysql 不是指 MySQL 服务,而是指 mysql 的客户端工具。

语法 :

https://dev.mysql.com/doc/refman/5.7/en/mysql-command-options.html

mysql [Options] [database]

参数 :
-u, --user=name ~ 指定用户名
-p, --password[=name] ~ 指定密码
-h, --host=name ~ 指定服务器 IP 或域名
-P, --port=# ~ 指定连接端口
eg.
mysql -h 127.0.0.1 -P 3306 -u root -p
mysql -h127.0.0.1 -P3306 -uroot -proot

  • 执行选项。

-e, --execute=name ~ 执行 SQL 语句并退出。

此选项可以在 MySQL 客户端执行 SQL 语句,而不用连接到 MySQL 数据库再执行,对于一些批处理脚本,这种方式尤其方便。

[geek@192 ~]$ mysql -uroot -proot demo_02 -e 'select * from tb_book';
mysql: [Warning] Using a password on the command line interface can be insecure.
+----+-------------------+--------------+--------+
| id | name              | publish_time | status |
+----+-------------------+--------------+--------+
|  1 | Java 编程思想      | 2088-09-09   | 1      |
|  2 | solr 编程思想      | 2088-09-09   | 0      |
|  3 | es                | NULL         | NULL   |
+----+-------------------+--------------+--------+
[geek@192 ~]$ 


mysqladmin。

mysqladmin 是一个执行管理操作的客户端程序。可以用它来检查服务器的配置和当前状态、创建并删除数据库等。

可以通过

mysqladmin --help

指令查看帮助文档。

[geek@192 ~]$ mysqladmin
mysqladmin  Ver 8.42 Distrib 5.7.29, for Linux on x86_64
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Administration program for the mysqld daemon.
Usage: mysqladmin [OPTIONS] command command....
  --bind-address=name IP address to bind to.
  -c, --count=#       Number of iterations to make. This works with -i
                      (--sleep) only.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       This is a non-debug version. Catch this and exit.
  --debug-info        This is a non-debug version. Catch this and exit.
  -f, --force         Don't ask for confirmation on drop database; with
                      multiple commands, continue even if an error occurs.
  -C, --compress      Use compression in server/client protocol.
  --character-sets-dir=name 
                      Directory for character set files.
  --default-character-set=name 
                      Set the default character set.
  -?, --help          Display this help and exit.
  -h, --host=name     Connect to host.
  -b, --no-beep       Turn off beep on error.
  -p, --password[=name] 
                      Password to use when connecting to server. If password is
                      not given it's asked from the tty.
  -P, --port=#        Port number to use for connection or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -r, --relative      Show difference between current and previous values when
                      used with -i. Currently only works with extended-status.
  --secure-auth       Refuse client connecting to server if it uses old
                      (pre-4.1.1) protocol. Deprecated. Always TRUE
  -s, --silent        Silently exit if one can't connect to server.
  -S, --socket=name   The socket file to use for connection.
  -i, --sleep=#       Execute commands repeatedly with a sleep between.
  --ssl-mode=name     SSL connection mode.
  --ssl               Deprecated. Use --ssl-mode instead.
                      (Defaults to on; use --skip-ssl to disable.)
  --ssl-verify-server-cert 
                      Deprecated. Use --ssl-mode=VERIFY_IDENTITY instead.
  --ssl-ca=name       CA file in PEM format.
  --ssl-capath=name   CA directory.
  --ssl-cert=name     X509 cert in PEM format.
  --ssl-cipher=name   SSL cipher to use.
  --ssl-key=name      X509 key in PEM format.
  --ssl-crl=name      Certificate revocation list.
  --ssl-crlpath=name  Certificate revocation list path.
  --tls-version=name  TLS version to use, permitted values are: TLSv1, TLSv1.1,
                      TLSv1.2
  --server-public-key-path=name 
                      File path to the server public RSA key in PEM format.
  --get-server-public-key 
                      Get server public key
  -u, --user=name     User for login if not current user.
  -v, --verbose       Write more information.
  -V, --version       Output version information and exit.
  -E, --vertical      Print output vertically. Is similar to --relative, but
                      prints output vertically.
  -w, --wait[=#]      Wait and retry if connection is down.
  --connect-timeout=# 
  --shutdown-timeout=# 
  --plugin-dir=name   Directory for client-side plugins.
  --default-auth=name Default authentication client-side plugin to use.
  --enable-cleartext-plugin 
                      Enable/disable the clear text authentication plugin.
  --show-warnings     Show warnings after execution

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- ----------------------------------------
bind-address                      (No default value)
count                             0
force                             FALSE
compress                          FALSE
character-sets-dir                (No default value)
default-character-set             auto
host                              (No default value)
no-beep                           FALSE
port                              0
relative                          FALSE
secure-auth                       TRUE
socket                            (No default value)
sleep                             0
ssl                               TRUE
ssl-verify-server-cert            FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-crl                           (No default value)
ssl-crlpath                       (No default value)
tls-version                       (No default value)
server-public-key-path            (No default value)
get-server-public-key             FALSE
user                              (No default value)
verbose                           FALSE
vertical                          FALSE
connect-timeout                   43200
shutdown-timeout                  3600
plugin-dir                        (No default value)
default-auth                      (No default value)
enable-cleartext-plugin           FALSE
show-warnings                     FALSE

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/my.cnf ~/.my.cnf 
The following groups are read: mysqladmin client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file,
                        except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#
                        Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.

Where command is a one or more of: (Commands may be shortened)
  create databasename	Create a new database
  debug			Instruct server to write debug information to log
  drop databasename	Delete a database and all its tables
  extended-status       Gives an extended status message from the server
  flush-hosts           Flush all cached hosts
  flush-logs            Flush all logs
  flush-status		Clear status variables
  flush-tables          Flush all tables
  flush-threads         Flush the thread cache
  flush-privileges      Reload grant tables (same as reload)
  kill id,id,...	Kill mysql threads
  password [new-password] Change old password to new-password in current format
  ping			Check if mysqld is alive
  processlist		Show list of active threads in server
  reload		Reload grant tables
  refresh		Flush all tables and close and open logfiles
  shutdown		Take server down
  status		Gives a short status message from the server
  start-slave		Start slave
  stop-slave		Stop slave
  variables             Prints variables available
  version		Get version info from server
[geek@192 ~]$ 



创建数据库。
[geek@192 ~]$ mysqladmin -uroot -proot create 'test01'
mysqladmin: [Warning] Using a password on the command line interface can be insecure.


删除数据库。
[geek@192 ~]$ mysqladmin -uroot -proot drop 'test01'
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.

Do you really want to drop the 'test01' database [y/N] y
Database "test01" dropped


mysqlbinlog。

由于服务器生成的二进制日志文件以二进制格式保存,所以如果想要检查这些文本的文本格式,就会使用到 mysqlbinlog 日志管理工具。

语法。

mysqlbinlog [options] log-files1 log-files2 …
选项:
-d, --database=name ~ 指定数据库名称,只列出指定的数据库相关操作。
-o, --offset=# ~ 忽略掉日志中的前 n 行命令。
-r,–result-file=name ~ 将输出的文本格式日志输出到指定文件。
-s, --short-form ~ 显示简单格式,省略掉一些信息。
–start-datatime=date1 --stop-datetime=date2 ~ 指定日期间隔内的所有日志。
–start-position=pos1 --stop-position=pos2 ~ 指定位置间隔内的所有日志。



mysqldump。

https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html

mysqldump 客户端程序用于执行逻辑备份,产生一组能够被执行以再现原始数据库对象定义和表数据的 SQL 语句。它转储一个或多个 MySQL 数据库以进行备份或转移到另一台 SQL 服务器。mysqldump 命令也可以生成 CSV 输出,其他分隔符的文本或 XML 格式。

shell> mysqldump [options] db_name [tbl_name ...]
shell> mysqldump [options] --databases db_name ...
shell> mysqldump [options] --all-databases
  • 连接选项。

-u, --user=name ~ 指定用户名。
-p, --password[=name] ~ 指定密码。
-h, --host=name ~ 指定服务器IP或域名。
-P, --port=# ~ 指定连接端口。

  • 输出内容选项。

–add-drop-database ~ 在每个数据库创建语句前加上 drop database 语句。
–add-drop-table 在每个表创建语句前加上 drop table 语句。默认开启。不开启(–
skip-add-drop-table)。
-n, --no-create-db ~ 不包含数据库的创建语句。
-t, --no-create-info ~ 不包含数据表的创建语句。
-d --no-data ~ 不包含数据。
-T, --tab=name 自动生成两个文件:一个 .sql 文件,创建表结构的语句;一个 .txt 文件,数据文件,相当于 select into outfile。

eg.

mysqldump -uroot -proot demo_02 tb_book --add-drop-database --add-drop-table > /tmp/tb_book.sql
mysqldump -uroot -proot -T /tmp demo_02 tb_book

mysqldump: Got error: 1290: The MySQL server is running with the --secure-file-priv option so it cannot execute this statement when executing ‘SELECT INTO OUTFILE’

解决。

[geek@192 geek]$ sudo vim /etc/my.cnf

加入

secure_file_priv =

mysqldump -uroot -proot -T /tmp demo_02 tb_book

[geek@192 geek]$ cat /tmp/tb_book.sql 
-- MySQL dump 10.13  Distrib 5.7.29, for Linux (x86_64)
--
-- Host: localhost    Database: demo_02
-- ------------------------------------------------------
-- Server version	5.7.29

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `tb_book`
--

DROP TABLE IF EXISTS `tb_book`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tb_book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `publish_time` date DEFAULT NULL,
  `status` varchar(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `tb_book`
--

LOCK TABLES `tb_book` WRITE;
/*!40000 ALTER TABLE `tb_book` DISABLE KEYS */;
INSERT INTO `tb_book` VALUES (4,'Java 编程思想','2088-09-09','1'),(5,'Python 编程思想','2088-09-08','0');
/*!40000 ALTER TABLE `tb_book` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2020-12-05  9:44:07
[geek@192 geek]$ 


mysqlimport / source。

mysqlimport 是客户端数据导入工具,用来导入mysqldump 加 -T 参数后导出的文本文件。

语法。

shell> mysqlimport [options] db_name textfile1 [textfile2 …]

表数据 ~ mysqlimport。
[geek@192 geek]$ mysqlimport -uroot -psQm581257. demo_02 /tmp/tb_book.txt


表结构 + 表数据 ~ source。
mysql> use demo_02;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> source /tmp/tb_book.sql

mysql> select * from tb_book;
+----+---------------------+--------------+--------+
| id | name                | publish_time | status |
+----+---------------------+--------------+--------+
|  4 | Java 编程思想       | 2088-09-09   | 1      |
|  5 | Python 编程思想     | 2088-09-08   | 0      |
+----+---------------------+--------------+--------+
2 rows in set (0.00 sec)




mysqlshow。

mysqlshow 客户端对象查找工具,用来很快地查找存在哪些数据库、数据库中的表、表中的列或者索引。

shell> mysqlshow [options] [db_name [tbl_name [col_name]]]

–count ~ 显示数据库及表的统计信息(数据库,表均可以不指定)。
-i ~ 显示指定数据库或者指定表的状态信息。

eg.

# 查询每个数据库的表的数量及表中记录的数量。
mysqlshow -uroot -proot --count
# 查询 test 库中每个表中的字段书,及行数。
mysqlshow -uroot -proot test --count
# 查询 test 库中 book 表的详细情况。
mysqlshow -uroot -proot test book --count
[geek@192 geek]$ mysqlshow -uroot -psQm581257. --count
mysqlshow: [Warning] Using a password on the command line interface can be insecure.
+--------------------+--------+--------------+
|     Databases      | Tables |  Total Rows  |
+--------------------+--------+--------------+
| information_schema |     61 |        15213 |
| demo_01            |     12 |      3000068 |
| demo_02            |      3 |           13 |
| mysql              |     31 |         3328 |
| performance_schema |     87 |        42771 |
| sakila             |     23 |        50086 |
| sys                |    101 |         5402 |
+--------------------+--------+--------------+
7 rows in set.
[geek@192 geek]$ mysqlshow -uroot -psQm581257. demo_02 --count
mysqlshow: [Warning] Using a password on the command line interface can be insecure.
Database: demo_02
+------------------+----------+------------+
|      Tables      | Columns  | Total Rows |
+------------------+----------+------------+
| tb_book          |        4 |          2 |
| tb_user          |        2 |          2 |
| test_innodb_lock |        3 |          9 |
+------------------+----------+------------+
3 rows in set.

[geek@192 geek]$ mysqlshow -uroot -psQm581257. demo_02 tb_book --count
mysqlshow: [Warning] Using a password on the command line interface can be insecure.
Database: demo_02  Wildcard: tb_book
+---------+----------+------------+
| Tables  | Columns  | Total Rows |
+---------+----------+------------+
| tb_book |        4 |          2 |
+---------+----------+------------+
1 row in set.

[geek@192 geek]$ mysqlshow -uroot -psQm581257. demo_02 tb_book -i
mysqlshow: [Warning] Using a password on the command line interface can be insecure.
Database: demo_02  Wildcard: tb_book
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------------+----------+----------------+---------+
| Name    | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation       | Checksum | Create_options | Comment |
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------------+----------+----------------+---------+
| tb_book | MyISAM | 10      | Dynamic    | 2    | 34             | 68          | 281474976710655 | 2048         | 0         | 6              | 2020-12-05 09:46:58 | 2020-12-05 09:46:58 |            | utf8_general_ci |          |                |         |
+---------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+-----------------+----------+----------------+---------+



MySQL 日志。

在任何一种数据库中,都会有各种各样的日志,记录着数据库工作的方方面面,以帮助数据库管理员追踪数据库曾经发生过的各种事件。MySQL 也不例外,在 MySQL 中,有 4 种不同的日志,分别是错误日志、二进制日志(BINLOG 日志)、查询日志和慢查询日志,这些日志记录着数据库在不同方面的踪迹。

错误日志。

错误日志是 MySQL 中最重要的日志之一,它记录了当 mysqld 启动和停止时,以及服务器在运行过程中发生任何严重错误时的相关信息。当数据库出现任何故障导致无法正常使用时,可以首先查看此日志。
该日志是默认开启的,默认存放目录为 mysql 的数据目录(/var/lib/mysql), 默认的日志文件名为 hostname.err(hostname 是主机名)。

mysql> show variables like 'log_error%';
+---------------------+---------------------+
| Variable_name       | Value               |
+---------------------+---------------------+
| log_error           | /var/log/mysqld.log |
| log_error_verbosity | 3                   |
+---------------------+---------------------+
2 rows in set (0.03 sec)



二进制日志。

https://dev.mysql.com/doc/refman/5.7/en/replication-options-binary-log.html

概述。

二进制日志(BINLOG)记录了所有的 DDL(数据定义语句)和 DML(数据操纵语句),但是不包括 DQL (数据查询语句)。此日志对于灾难时的数据恢复起着极其重要的作用,MySQL 的主从复制, 就是通过该 binlog 实现的。

二进制日志,默认情况下是没有开启的,需要到 MySQL 的配置文件中开启,并配置 MySQL 日志的格式。

配置文件位置 ~ /usr/my.cnf。

日志存放位置 ~ 配置时,给定了文件名但是没有指定路径,日志默认写入 MySQL 的数据目录。

mysql> show variables like 'log_error%';
+---------------------+---------------------+
| Variable_name       | Value               |
+---------------------+---------------------+
| log_error           | /var/log/mysqld.log |
| log_error_verbosity | 3                   |
+---------------------+---------------------+
2 rows in set (0.01 sec)

sudo vim /usr/my.cnf

# 配置开启 binlog 日志,日志的文件前缀为 mysqlbin。生成的文件名如:mysqlbin.000001、mysqlbin.000002
log_bin = mysqlbin
# 配置二进制日志的格式。
binlog_format = STATEMENT

–log-bin[=base_name]

Command-Line Format ~ --log-bin=file_name
Type ~ File name

  • 测试。
[geek@192 geek]$ mysql -uroot -psQm581257.
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.29 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> use demo_02;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+-------------------+
| Tables_in_demo_02 |
+-------------------+
| tb_book           |
| tb_user           |
| test_innodb_lock  |
+-------------------+
3 rows in set (0.00 sec)

mysql> insert into tb_book values (null, 'Lucene', '2020-09-09', '0');
Query OK, 1 row affected (0.01 sec)

mysql> select * from tb_book;
+----+---------------------+--------------+--------+
| id | name                | publish_time | status |
+----+---------------------+--------------+--------+
|  4 | Java 编程思想       | 2088-09-09   | 1      |
|  5 | Python 编程思想     | 2088-09-08   | 0      |
|  6 | Lucene              | 2020-09-09   | 0      |
+----+---------------------+--------------+--------+
3 rows in set (0.00 sec)

mysqlbinlog mysqlbin.000001



日志格式。
  • STATEMENT。

该日志格式在日志文件中记录的都是 SQL 语句(statement),每一条对数据进行修改的 SQL 都会记录在日志文件中,通过 MySQL 提供的 mysqlbinlog 工具,可以清晰的查看到每条语句的文本。主从复制的时候,从库(slave)会将日志解析为原文本,并在从库重新执行一次。

  • ROW。

该日志格式在日志文件中记录的是每一行的数据变更,而不是记录 SQL 语句。比如,执行 SQL 语句:update tb_book set status = ‘1’;, 如果是 STATEMENT 日志格式,在日志中会记录一行 SQL 文件;如果是 ROW,由于是对全表进行更新,也就是每一行记录都会发生变更,ROW 格式的日志中会记录每一行的数据变更。

sudo vim /usr/my.cnf

# 配置开启 binlog 日志,日志的文件前缀为 mysqlbin。生成的文件名如:mysqlbin.000001、mysqlbin.000002
log_bin = mysqlbin
# 配置二进制日志的格式。
binlog_format = ROW

如果日志格式是 ROW , 直接查看数据 , 是查看不懂的 ; 可以在mysqlbinlog 后面加上参数 -vv。

1 mysqlbinlog -vv mysqlbin.000002
  • MIXED。

这是目前 MySQL 默认的日志格式,即混合了 STATEMENT 和 ROW 两种格式。默认情况下采用 STATEMENT,但是在一些特殊情况下采用 ROW 来进行记录。MIXED 格式能尽量利用两种模式的优点,而避开他们的缺点。



日志读取。

由于日志以二进制方式存储,不能直接读取,需要用 mysqlbinlog 工具来查看。



日志删除。

对于比较繁忙的系统,由于每天生成日志量大,这些日志如果长时间不清除,将会占用大量的磁盘空间。下面我们将会讲解几种删除日志的常见方法。

  • 方式 ~ Reset Master。

通过 Reset Master 指令删除全部 binlog 日志,删除之后,日志编号将从 xxxx.000001重新开始 。

$ reset master
  • 方式 ~ 执行指令 purge master logs to ‘mysqlbin.******’,该命令将删除 ****** 编号之前的所有日志。

  • 方式 ~ 执行指令 purge master logs before ‘yyyy-mm-dd hh24:mi:ss’ ,该命令将删除日志为 “yyyy-mm-dd hh24:mi:ss” 之前产生的所有日志。

  • 方式 ~ 设置参数 --expire_logs_days=#,此参数的含义是设置日志的过期天数,过了指定的天数后日志将会被自动删除,这样将有利于减少 DBA 管理日志的工作量。

# 配置开启 binlog 日志,日志的文件前缀为 mysqlbin。生成的文件名如:mysqlbin.000001、mysqlbin.000002
log_bin = mysqlbin
# 配置二进制日志的格式。
binlog_format = ROW
--expire_logs_days = 3


查询日志。

查询日志中记录了客户端的所有操作语句,而二进制日志不包含查询数据的 SQL 语句。
默认情况下,查询日志是未开启的。如果需要开启查询日志,可以设置以下配置。

# 该选项用来开启查询日志。可选值 ~ 0 或者 1。0 代表关闭,1 代表开启。
general_log = 1
# 设置日志的文件名。如果没有指定,默认的文件名为 host_name.log。
general_log_file = query_log.log
[geek@192 ~]$ sudo cat /var/lib/mysql/query_log.log
/usr/sbin/mysqld, Version: 5.7.29-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
2020-12-05T02:46:55.584946Z	    2 Connect	root@localhost on  using Socket
2020-12-05T02:46:55.585303Z	    2 Query	select @@version_comment limit 1
2020-12-05T02:47:03.787980Z	    2 Query	SELECT DATABASE()
2020-12-05T02:47:03.788511Z	    2 Init DB	demo_02
2020-12-05T02:47:03.789653Z	    2 Query	show databases
2020-12-05T02:47:03.790982Z	    2 Query	show tables
2020-12-05T02:47:03.791276Z	    2 Field List	tb_book 
2020-12-05T02:47:03.804147Z	    2 Field List	tb_user 
2020-12-05T02:47:03.804894Z	    2 Field List	test_innodb_lock 
2020-12-05T02:47:12.299256Z	    2 Query	show tables
2020-12-05T02:47:21.256226Z	    2 Query	select * from tb_book
2020-12-05T02:47:32.479768Z	    2 Query	select * from tb_book where id = 1
2020-12-05T02:47:35.893986Z	    2 Query	select * from tb_book where id = 4
2020-12-05T02:48:04.055322Z	    2 Query	update tb_book set status = '1'



慢查询日志。

慢查询日志记录了所有执行时间超过参数 long_query_time 设置值并且扫描记录数不小于
min_examined_row_limit 的所有的 SQL 语句的日志。long_query_time 默认为 10 秒,最小为 0,精度可以到微秒。

慢查询日志默认是关闭的。可以通过两个参数来控制慢查询日志。

# 该参数用来控制慢查询日志是否开启。可取值 ~ 1 和 0。1 ~ 开启,0 ~ 关闭。
slow_query_log = 1
# 该参数用来指定慢查询日志的文件名。
slow_query_log_file = slow_query.log
# 该选项用来配置查询的时间限制。超过这个时间将认为值慢查询,将需要进行日志记录,默认 10s。
long_query_time = 10
  • 测试。
mysql> use demo_01
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> select * from tb_item where title like '% 2999991 号';
+---------+--------------------+-------+-----+------------+--------+------------+---------------------+---------------------+
| id      | title              | price | num | categoryid | status | sellerid   | createtime          | updatetime          |
+---------+--------------------+-------+-----+------------+--------+------------+---------------------+---------------------+
| 2999991 | 商品 2999991| 67.14 |  32 |          5 | 1      | 2450702011 | 2020-09-09 19:19:19 | 2020-09-09 19:19:19 |
+---------+--------------------+-------+-----+------------+--------+------------+---------------------+---------------------+
1 row in set (2.05 sec)
[geek@192 ~]$ sudo cat /var/lib/mysql/slow_query.log
/usr/sbin/mysqld, Version: 5.7.29-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
/usr/sbin/mysqld, Version: 5.7.29-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
/usr/sbin/mysqld, Version: 5.7.29-log (MySQL Community Server (GPL)). started with:
Tcp port: 0  Unix socket: /var/lib/mysql/mysql.sock
Time                 Id Command    Argument
# Time: 2020-12-05T03:01:00.804014Z
# User@Host: root[root] @ localhost []  Id:     2
# Query_time: 2.038394  Lock_time: 0.000199 Rows_sent: 1  Rows_examined: 3000000
use demo_01;
SET timestamp=1607137260;
select * from tb_item where title like '% 2999991 号';



日志的读取。

和错误日志、查询日志一样,慢查询日志记录的格式也是纯文本,可以被直接读取。

查询 long_query_time 的值。

mysql> show variables like 'long%';
+-----------------+-----------+
| Variable_name   | Value     |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
1 row in set (0.01 sec)



MySQL 复制。

《MySQL 复制。》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lyfGeek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值