www.colben.cn/content/post/mysql-binlog.md
2021-11-14 14:32:08 +08:00

87 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "Mysql 二进制日志"
date: 2019-10-30T11:05:08+08:00
lastmod: 2019-10-30T11:05:08+08:00
keywords: []
tags: ["mysql", "binlog"]
categories: ["database"]
---
# MySQL 5.7 开启 binlog
- 修改 my.cnf 文件
```
[mysqld]
log-bin=[/存放目录/]mysql-bin #注意 mysql 可读写“存放目录”,默认数据存放目录
expire-logs-days=7 #保留7天内修改过的 binglog 文件
max-binlog-size=512M #单个 binlog 文件大小上限默认1G
#指定或忽略要复制的数据库,存在跨库问题
binlog-do-db=db1
binlog-db-db=db2
#binlog-ignore-db=db1
#binlog-ignore-db=db2
```
# 常用操作
- 查看所有 binlog 文件列表
```sql
show master logs;
```
- 查看 master 状态,包含最新 binlog 文件名和 position
```sql
show master status;
```
- 清除过期 binlog 文件,并使用新编号的 binlog 文件开始记录日志
```sql
flush logs;
```
- 删除 binlog 文件
- 删除旧的 binlog 文件
```sql
purge master logs to 'mysql-bin.000573';
purge master logs before '2018-04-18 06:00:00';
purge master logs before DATE_SUB(NOW(), INTERVAL 2 DAY);
```
- 清空所有 binlog 文件
```sql
reset master
```
# 使用 mysqlbinlog 命令查看 binlog 文件的内容
- 使用
```bash
# 查看日志
mysqlbinlog [选项] binlog文件名
# 恢复数据
mysqlbinlog [选项] binlog文件名 | mysql -u用户名 -p密码 -D数据库 [-v]
```
- 常用选项
- --start-position=128 起始 pos
- --stop-position=256 结束 pos
- --start-datetime="2018-08-08 00:00:00" 起始时间
- --stop-datetime="2018-08-09 12:00:00" 结束时间
- --database=db_name 只恢复 db_name 数据库
# 使用 sql 查看 binlog 文件的内容
- 查询语句
```sql
SHOW BINLOG EVENTS [IN 'log_name'] [FROM pos] [LIMIT [offset,] row_count];
```
- 选项
- log_name binlog文件名默认第一个 binlog 文件
- pos 查询起始 pos默认 log_name 中的第一个 pos
- offset 偏移 pos 个数
- row_count 查询数量
# 调整 binlog_cache_size
- 查看当前 binlog_cache_size 大小(byte),默认 32k
```sql
show variables like 'binlog_cache_size';
```
- 查看当前 binlog_cache_use 和 binlog_cache_disk_use 次数
```sql
show status like 'binlog_cache%';
-- binlog_cache_disk_use 使用临时文件写 binlog 文件的次数
-- binlog_cache_use 使用缓存写 binlog 文件的次数
```