Mysql Binlog 日志

使用场景

  • MySQL主从复制,Master节点开启binlog日志记录,然后同步到slave节点
  • MySQL数据恢复,使用mysqlbinlog工具来恢复数据

binlog 操作命令

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# 是否启用binlog日志
show variables like 'log_bin';

# 查看详细的日志配置信息
show global variables like '%log%';

# mysql数据存储目录
show variables like '%dir%';

# 查看binlog的目录
show global variables like "%log_bin%";

# 查看当前服务器使用的biglog文件及大小
show binary logs;

# 查看最新一个binlog日志文件名称和Position
show master status;

# 查看 binlog 日志列表
show master logs;

# 事件查询命令
# IN 'log_name' :指定要查询的binlog文件名(不指定就是第一个binlog文件)
# FROM pos :指定从哪个pos起始点开始查起(不指定就是从整个文件首个pos点开始算)
# LIMIT [offset,] :偏移量(不指定就是0)
# row_count :查询总条数(不指定就是所有行)
show binlog events [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count];

show binlog events in 'mysql-bin.000001' limit 6\G;

# 查看 binlog 内容
show binlog events;

# 查看具体一个binlog文件的内容 (in 后面为binlog的文件名)
show binlog events in 'mysql-bin.000003';

# 设置binlog文件保存事件,过期删除,单位天
set global expire_log_days=3; 

# 刷新 binlog 日志
flush logs;

# 删除当前的binlog文件
reset master; 

# 删除slave的中继日志
reset slave;

# 删除指定日期前的日志索引中binlog日志文件
purge master logs before '2020-11-22 23:39:53';

# 删除指定日志文件
purge master logs to 'mysql-bin.000003';

mysqlbinlog 命令操作

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# 命令行查看binlog二进制文件
/usr/local/mysql/bin/mysqlbinlog -v --base64-output=decode-rows /usr/local/mysql/data/mysql-bin.000001

# 过滤查看指定位置
/usr/local/mysql/bin/mysqlbinlog /usr/local/mysql/data/mysql-bin.000001 | grep -A 10 "at 654$"

# 指定时间恢复数据到mysql
mysqlbinlog --start-date="2020-11-22 23:26:07" --stop-date="2020-11-22 23:26:26" mysql-bin.000001 | mysql -uroot -p123456 -h127.0.0.1

# 指定pos位置和数据库恢复数据到文件中
mysqlbinlog --start-date="2020-11-22 23:26:07" --stop-date="2020-11-22 23:26:26" --database=mysql mysql-bin.000001 > /tmp/log.sql

# 指定pos位置恢复数据
mysqlbinlog --start-positon="50" --stop-position="100" mysql-bin.000001 | mysql -uroot -p123456 -h127.0.0.1

参考