Sub topic 13
Logging and monitoring the server
This chapter assumes you can already install and start PostgreSQL or MySQL under systemd, edit the main configuration file, and read basic SQL output. Logs and monitoring answer two questions: what happened, and what is happening now. Without them, you find out about a full disk, a connection limit or a slow query when users complain.
Where the signals come from
A database server gives you four kinds of signal:
- The service log. Startup, shutdown, crashes and configuration errors. Under systemd this is in the journal.
- The engine's own log file. Errors, slow statements, lock waits and connection events. You decide how much it records.
- Built-in statistics. Views and status counters you query with SQL.
- Host metrics. Disk space, memory, CPU and I/O from the operating system.
Finding the logs
Check the journal first. It captures the service's output even when the engine's own log file is misconfigured.
sudo journalctl -u postgresql --since '1 hour ago'
sudo journalctl -u mysql --since '1 hour ago' -p warningDebian and Ubuntu packages also write engine log files. PostgreSQL writes to /var/log/postgresql/postgresql-<version>-main.log. MySQL writes to /var/log/mysql/error.log. Other distributions use different paths, and some use the unit name mysqld or mariadb. Ask the server where it logs instead of guessing.
-- PostgreSQL
SHOW logging_collector;
SHOW log_directory;
-- MySQL
SHOW GLOBAL VARIABLES LIKE 'log_error';Making the PostgreSQL log useful
The defaults record errors and little else. These settings add the context you need to investigate problems.
# postgresql.conf
log_line_prefix = '%m [%p] %u@%d %h '
log_min_duration_statement = 500
log_connections = on
log_disconnections = on
log_checkpoints = on
log_lock_waits = on
log_temp_files = 0log_line_prefixstamps each line with the time (%m), process ID (%p), user and database (%u@%d) and client host (%h).log_min_duration_statementlogs any statement that runs longer than the given number of milliseconds. A value of 500 logs statements over half a second. A value of 0 logs every statement and can flood the disk.log_connectionsandlog_disconnectionsshow who connects and for how long. They help you spot connection storms and failed logins.log_lock_waitslogs a message when a session waits longer thandeadlock_timeout(1 second by default) for a lock.log_temp_files = 0logs every temporary file a query spills to disk. Spills suggest thatwork_memis too small for some queries.
Most of these settings need only a reload, not a restart:
sudo systemctl reload postgresqlMaking the MySQL log useful
MySQL's error log is on by default. The slow query log is off by default and is the most valuable one to enable.
# [mysqld] section
[mysqld]
slow_query_log = ON
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
log_error = /var/log/mysql/error.loglong_query_time is in seconds and accepts fractions such as 0.5. You can enable the slow log without a restart:
SET GLOBAL slow_query_log = ON;
SET GLOBAL long_query_time = 1;A SET GLOBAL change is lost at restart, so also put it in the configuration file. To summarize the slow log, sort by total time:
sudo mysqldumpslow -s t -t 10 /var/log/mysql/slow.logLooking at live activity
Statistics views show the current state without waiting for a log line. Run these when someone reports that the database is slow.
-- PostgreSQL: active statements, longest first
SELECT pid, usename, datname, state,
now() - query_start AS runtime,
left(query, 60) AS query
FROM pg_stat_activity
WHERE state <> 'idle'
ORDER BY runtime DESC;
-- PostgreSQL: connections in use against the limit
SELECT count(*) AS in_use,
current_setting('max_connections') AS max_connections
FROM pg_stat_activity
WHERE backend_type = 'client backend';-- MySQL: running statements
SHOW FULL PROCESSLIST;
-- MySQL: connection pressure
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW GLOBAL STATUS LIKE 'Max_used_connections';
SHOW GLOBAL STATUS LIKE 'Aborted_connects';
SHOW GLOBAL VARIABLES LIKE 'max_connections';Compare Max_used_connections with max_connections. If the peak is close to the limit, the server is about to refuse clients. A rising Aborted_connects usually means wrong passwords, a blocked network path or clients that give up early.
What to monitor and alert on
Watch a short list of signals. Each one points to a failure you can prevent.
| Signal | Why it matters | Where to read it |
|---|---|---|
| Free space on the data volume | A full disk stops writes and can crash the server | `df -h` on the data directory |
| Free space on the log volume | Verbose logging can fill it | `df -h /var/log` |
| Connections in use vs. limit | At the limit, new clients are refused | `pg_stat_activity`, `Threads_connected` |
| Longest-running statement | Finds stuck or runaway queries | `pg_stat_activity`, `PROCESSLIST` |
| Replication lag | A lagging replica serves old data | `pg_stat_replication`, `SHOW REPLICA STATUS` |
| Last successful backup | A silent backup failure is found at restore time | Backup job exit code and file age |
| Service state | The server may be down | `systemctl is-active` |
Alert on conditions that need a human, for example "data volume above 85 percent" or "no successful backup in 26 hours". Do not alert on every spike, because people learn to ignore noisy alerts.
A minimal check you can run from cron or a monitoring agent:
#!/usr/bin/env bash
# Exit non-zero if the database service is down or the data volume is nearly full.
set -euo pipefail
systemctl is-active --quiet postgresql || { echo "postgresql is not active"; exit 2; }
used=$(df --output=pcent /var/lib/postgresql | tail -1 | tr -dc '0-9')
if [ "$used" -ge 85 ]; then
echo "data volume at ${used}%"
exit 1
fi
echo "ok"Change the path and unit name for your layout, for example /var/lib/mysql and mysql.
Keeping logs under control
Logs grow without limit unless something rotates them. Debian packages install a logrotate rule for each engine. Confirm it exists and review its schedule:
ls /etc/logrotate.d/ | grep -E 'postgresql|mysql'
sudo logrotate --debug /etc/logrotate.d/postgresql-commonIf you enable a custom slow log path, add a logrotate rule for it. Otherwise the file is never rotated. Rotation must also tell the server to reopen the file. Otherwise it keeps writing to the old, renamed file.
Logs hold sensitive data. Statements logged by log_min_duration_statement or the slow log include literal values such as email addresses. Restrict log file permissions and treat the logs like the data itself.
Common mistakes
- Setting
log_min_duration_statement = 0on a busy server. The log grows by gigabytes per hour and slows the host. - Enabling a slow log in a configuration file but never rotating it.
- Watching only service state. A server can be "active" while it refuses every connection because it is at
max_connections. - Putting logs on the same volume as the data. A log flood then fills the data disk.
- Forgetting that
SET GLOBALin MySQL does not persist across restarts.
Exercise
Users report the application is slow every afternoon. Your PostgreSQL server has default logging. Which two settings do you change first, how do you apply them, and where do you look for the cause?
Show answer
Set logmindurationstatement to a threshold such as 500 (milliseconds) and loglockwaits to on. Apply them with sudo systemctl reload postgresql, since neither needs a restart. Then read the engine log for statements over the threshold and for lock-wait messages during the slow period. While the slowness is happening, also query pgstat_activity for the longest-running active statements.
Exercise
A MySQL server shows Maxusedconnections equal to max_connections, and the application logs "Too many connections". Which counters confirm the problem, and what are two reasonable responses?
Show answer
Compare Threadsconnected and Maxusedconnections with the maxconnections variable. If the peak equals the limit, the server has refused clients. Responses: find and fix clients that leak or hold idle connections, put a connection pool in front of the server, or raise max_connections only after checking that memory per connection allows it.