# MariaDB slow query logging and journald rotation

LLMS index: [llms.txt](/en/llms.txt)

---

Setting up very slow query logging in MariaDB demands attention to CNF flags and rotation logic; otherwise the log fast becomes noise. This note walks through the minimal commands to enable logging without a restart, format configuration, journald rotation, and cleanup via logrotate.

## Включение very slow queries в CNF без перезапуска

In MariaDB 10.5+ flags can be changed dynamically via `SET GLOBAL`, avoiding a service restart. For persistent configuration, edit the CNF file (typically `/etc/mysql/mariadb.conf.d/50-server.cnf` or the distro‑specific equivalent):

```
[mysqld]
slow_query_log=1
slow_query_log_file=/var/log/mysql/mariadb-slow.log
long_query_time=1
log_queries_not_using_indexes=1
```

After changing CNF, restart MariaDB: `sudo systemctl restart mariadb`.

| Флаг | Значение | Описание |
|------|----------|----------|
| `slow_query_log` | `1` | Enables slow query logging |
| `slow_query_log_file` | `/var/log/mysql/mariadb-slow.log` | Path to the log file |
| `long_query_time` | `1` | Minimum duration in seconds |
| `log_queries_not_using_indexes` | `1` | Log queries that don’t use an index |

> [!TIP]
> After changing dynamic flags verify with `SHOW VARIABLES LIKE 'slow_query_log';` and `tail -n 3 /var/log/mysql/mariadb-slow.log`.

## Формат вывода лога и настройка файла

The slow query log format is determined by the `log_output` setting. By default MariaDB writes to a file in plain text; ensure the directory `/var/log/mysql/` and the log file have ownership of the `mysql` user and group, with permissions `0640` or `0640`‑restricted so the daemon can write and admins can read. If `log_output` is set to `TABLE`, queries are stored in the `mysql.slow_log` table and can be queried with `SELECT * FROM mysql.slow_log ORDER BY start_time DESC LIMIT 10;`. When forwarding to journald, the file‑based log can be tailed by a systemd service or via `systemd-cat`, but the native file format remains newline‑delimited `SET timestamp|user@host\host[pid]...\query` per connection. Verify the active format with `SHOW VARIABLES LIKE 'log_output';` and adjust the CNF `log_output` flag accordingly before restarting.

> [!WARNING]
> Switching `log_output` to `TABLE` or `FILE` mid‑run may truncate the existing file depending on the `sql_log_off` state; always check the error log after a change.

## Настройка ротации journald (Size/Count)

Journald rotation is governed by `/etc/journald.conf` and drop‑in overrides in `/etc/journald.conf.d/`. The `Size=` and `Count=` directives cap the total journal storage: when the size limit is reached, oldest entries are purged to keep only the last `Count` archives. For MariaDB logs injected into the journal (e.g., via `systemd-cat < /var/log/mysql/mariadb-slow.log` or a custom service wrapper), the same limits apply. A typical override drop‑in `10-mariadb-slow.conf` may set `Size=50M` and `Count=3`, retaining roughly the last 150 MB of slow‑query entries across rotations. Reload the daemon with `sudo systemctl restart systemd-journald` after editing.

> [!NOTE]
> If MariaDB writes directly to a file and you rely on logrotate for file‑level rotation, keep journald `Size`/Count separate to avoid double‑rotation or lost entries.

## Скрипт очистки старых логов через logrotate

A `logrotate` snippet under `/etc/logrotate.d/mariadb-slow` handles file‑based rotation independently of journald:

```
/var/log/mysql/mariadb-slow.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0640 mysql mysql
    postrotate
        systemctl reload mariadb.service >/dev/null 2>&1 || true
    endscript
}
```

The `daily` cycle, `rotate 7` retention, and `compress`/`delaycompress` keep the most recent week of logs while freeing disk space. The `postrotate` block ensures MariaDB reopens the log file after rotation without a full restart. Run `sudo logrotate -f /etc/logrotate.d/mariadb-slow` to force a cycle test.

> [!TIP]
> Verify rotation with `ls -l /var/log/mysql/mariadb-slow.log*` after the first forced run and confirm the old file was compressed and a new empty file created with the correct ownership.

## Чего избегать: шумы от отсутствующих индексов

The `log_queries_not_using_indexes=1` flag captures every full‑table scan, which on busy or poorly indexed schemas generates disproportionate log volume and I/O. In production this often masks genuine performance problems rather than solving them. Before enabling the flag, run `pt-query-digest` or `EXPLAIN` on representative queries to identify missing indexes, add covering indexes where feasible, and consider raising `long_query_time` to a higher threshold (e.g., `2` or `5` seconds) to focus on the most impactful queries. Monitor the log growth rate after enabling; if daily size exceeds a few megabytes, reevaluate index strategy before relying on this flag as a long‑term solution.
