## 实验环境


此次实验的环境如下

- MySQL 5.7.25

- Redhat 6.10

- binlog模式采用row模式

前面的一些章节我们对mysqldump常用命令进行了讲解


这个专题的内容为mysqlbinlog命令的详解

mysqlbinlog是MySQL中用来处理binlog的工具

这节内容讲如何读取远程MySQL服务器日志


## 1.  mysqlbinlog连接参数

使用 --read-from-remote-server 读取远程数据库日志,而不是读取本地文件

或者 -R 参数

当然我们可以用他来连接本地数据库来读取日志文件

需要搭配如下连接参数来使用


 - --host 

 - --password 

 - --port, 

 - --protocol

 - --socket 

 - --user

注意如果没有--read-from-remote-server 参数,则上面的连接参数被忽略

这个参数需要远程数据库开启,而且只能读取binlog,不能读取relay log

连接的用户需要有连接远程数据库的权限


## 2. 连接远程数据库日志(读取后断开)

```
mysqlbinlog --read-from-remote-server --host  11.12.14.29 --user system --password  --port 3306  --protocol=tcp  -vv mysql-bin.000001
```

[image:576 size:orig]



命令执行后提示输入密码,之后即可看到binlog内容

注意需要加上binlog文件名称,不要使用绝对路径

我们同样可以使用start_position start_datetime 等参数来指定读取log的区间

我们可以使用--result-file参数指定输出到文件

```
mysqlbinlog --read-from-remote-server --host  11.12.14.29 --user system --password  --port 3306  --protocol=tcp  -vv mysql-bin.000001 --result-file=/tmp/output.sql
```
## 3. 持续读取远程数据库日志

上面的命令执行完成后退出mysqlbinlog命令行

我们可以使用--stop-never参数来持续读取远程数据库的日志

```
mysqlbinlog --read-from-remote-server --host  11.12.14.29 --user system --password  --port 3306  --protocol=tcp  --stop-never  -vv mysql-bin.000001
```
命令执行后提示输入密码,之后即可看到binlog内容

该参数会默认加上--to-last-log参数,即mysqlbinlog会自动一直读取到远程数据库的最后一个日志文件

这时如果远程数据库有操作,则会持续显示出来


[image:577 size:orig]

我们可以使用--result-file参数指定输出到文件
```
mysqlbinlog --read-from-remote-server --host  11.12.14.29 --user system --password  --port 3306  --protocol=tcp  --stop-never  -vv mysql-bin.000001 --result-file=/tmp/output.sql
```
## 4. 参考链接


[https://dev.mysql.com/doc/refman/5.7/en/mysqlbinlog.html](https://dev.mysql.com/doc/refman/5.7/en/mysqlbinlog.html)

好了 今天的内容就说到这里,下节再见