# MySQL slow_log日志采集方案

LLMS 索引： [llms.txt](/llms.txt)

---

# 1 MySQL slow_log日志采集方案

## 1.1 背景

慢查询对线上的影响很大，而慢日志是发现慢查询SQL的最常用手段，所以对慢日志的收集和监控，是作为一个DBA的最常见需求。下面介绍一下常见的慢日志收集方案

> - [slow-query-log](https://dev.mysql.com/doc/refman/5.7/en/slow-query-log.html)
> - [5.4.1 Selecting General Query Log and Slow Query Log Output Destinations](https://dev.mysql.com/doc/refman/5.7/en/log-destinations.html)
> - [5.4.7 Server Log Maintenance](https://dev.mysql.com/doc/refman/5.7/en/log-file-maintenance.html)

## 1.2 方案一：将日志写入到表中，从表中定时获取慢查询

### 1.2.1 1. 开启方法

```mysql
set global long_query_time=2;
set global slow_query_log=ON;
set global log_output='TABLE';
```

### 1.2.2 优点

1. 查询灵活： 可以通过SQL来搜索满足条件的慢日志
2. 采集方便：不需要额外组件支持，就可以远程查看慢日志

## 1.3 方案二：将日志输出到文件，使用filebeat来获取日志信息

- [rotating-mysql-slow-logs-safely](https://www.percona.com/blog/2013/04/18/rotating-mysql-slow-logs-safely/)
- [mysql-slow-query-log-tools-and-tips](https://www.percona.com/blog/2014/03/14/mysql-slow-query-log-tools-and-tips/)
- [rotating-mysql-slow-query-log](https://minervadb.com/index.php/2018/04/19/rotating-mysql-slow-query-log/)

### 1.3.1 1. 开启方法

```mysql
set global long_query_time=2;
set global slow_query_log=ON;
set global log_output='FILE';
set global slow_query_log_file='slow_log.log';
```

### 1.3.2 2. 配套设施

> 如果使用Docker来运行MySQL和filebeat，需要在filebeat里挂载MySQL的日志目录，这个也比较坑。

- [Filebeat实现MySQL日志轻量化发送至Elasticsearch](https://developer.aliyun.com/article/762984)

#### 1.3.2.1 2.1 日志采集

日志采集有多种组件，其中filebeat天然支持MySQL的慢日志，可以直接输出到ES中。

- [filebeat采集格式](https://www.elastic.co/guide/en/beats/filebeat/current/exported-fields-mysql.html)
- [filebeat镜像](registry.yingmi-inc.com/infra/filebeat:7.9.1)

```yaml
# vim /etc/filebeat/modules.d/mysql.yml
- module: mysql
  # Error logs
  error:
    enabled: true
    var.paths: ["/var/log/mysql/mysqld.log"]
    # Set custom paths for the log files. If left empty,
    # Filebeat will choose the paths depending on your OS.
    #var.paths:

  # Slow logs
  slowlog:
    enabled: true
    var.paths: ["/var/log/mysql/slow-log.log"]
    # Set custom paths for the log files. If left empty,
    # Filebeat will choose the paths depending on your OS.
    #var.paths:
```

#### 1.3.2.2 2.2 日志滚动logratate

> - [logrotate man page](https://linux.die.net/man/8/logrotate)

因为MySQL慢日志默认不会自己进行滚动，如果一直持续写入的话，单个日志文件会很大

```
/var/lib/mysql/localhost-slow.log {
    size 100M
    dateext
	dateformat -%Y%m%d_%s
    compress
    missingok
    rotate 10
    notifempty
    sharedscripts
    copytruncate
}
```
