Skip to content
$ lynuxpro
← Linux

LESSON 19 OF 26 · ADVANCED · 16 MIN

Log management and rotation

In one minute

  • Logs are the diary of a server: what happened, when and why. Log management means keeping them in the right place, at a sensible size, and sending copies to a central system.
  • Logs left alone grow until the disk is full, and they disappear when a server dies. Managed logs are your evidence in every incident.
  • journald collects logs, rsyslog writes them into text files, logrotate renames, compresses and deletes old files on a schedule, and a log agent sends copies to a central system such as Loki, Elasticsearch or CloudWatch.
  • 👉 Setting up any new app, fixing a full disk, and building monitoring.

Think of it like: a shop's receipt roll. Each day you tear off the old roll, file it in a box (compress), throw away boxes older than two weeks (delete), and send a copy to head office (central logging).

Where logs live

👉 The first place to look when you investigate anything on a server.

LocationWhat is in it
/var/log/syslog (Debian) or /var/log/messages (RHEL)General system messages
/var/log/auth.log or /var/log/secureLogins, sudo, SSH
/var/log/kern.logKernel messages
/var/log/nginx/, /var/log/apache2/Web server access and error logs
/var/log/dpkg.log, /var/log/dnf.logPackage installs
The systemd journalEverything from systemd services (read with journalctl)
/var/lib/docker/containers/*/*-json.logWhat Docker containers print
ls -lh /var/logtail -n 5 /var/log/auth.log
SHELLbashutf-8 · 2L

journald and rsyslog

Two programs that work together on most servers:

  • journald collects logs from all services and the kernel. It stores them in a special (binary) format that you read with journalctl.
  • rsyslog writes normal text files into /var/log, and can send logs to other servers.

How they connect: journald receives the messages first, then passes them to rsyslog to write the text files.

When to tune it: Make the journal survive reboots and cap its size, in /etc/systemd/journald.conf:

[Journal]Storage=persistentSystemMaxUse=1GMaxRetentionSec=14day
NORMALconfutf-8 · 4L
  • Storage=persistent = keep logs after a reboot.
  • SystemMaxUse=1G = never use more than 1 GB.
  • MaxRetentionSec=14day = delete logs older than 14 days.

Clean up straight away when needed:

journalctl --disk-usagesudo journalctl --vacuum-size=500Msudo journalctl --vacuum-time=7d
OUTPUTterminalutf-8 · 3L

Severity levels

Every log message has a level that says how serious it is.

LevelNameUse
0emergThe system cannot be used
1alertAct immediately
2critCritical problem
3errError
4warningWarning
5noticeNormal, but worth noting
6infoInformation
7debugDetail for debugging

Remember it: Lower number = more serious. 0 is "the house is on fire", 7 is "just chatting".

journalctl -p warning shows warnings and everything more serious. You can write your own messages into the log with logger:

logger -p user.err "backup failed: disk full"
OUTPUTterminalutf-8 · 1L

logrotate: keeping files under control

logrotate renames, compresses and deletes old log files on a schedule, so they never fill the disk.

Without it, one busy app log can grow to tens of gigabytes.

It runs daily (from a systemd timer or cron) and follows the rules in /etc/logrotate.conf and /etc/logrotate.d/.

👉 Every custom app you install needs its own rule.

A rule for your app, /etc/logrotate.d/orders:

/var/log/orders/*.log {    daily    rotate 14    compress    delaycompress    missingok    notifempty    maxsize 500M    create 0640 orders orders    postrotate        systemctl kill -s HUP orders.service    endscript}
OUTPUTterminalutf-8 · 13L
LineMeaning
daily / weeklyHow often to rotate
rotate 14Keep 14 old files
compress / delaycompressZip old files, but leave the most recent old one unzipped (easier to read)
maxsize 500MRotate early if the file grows past 500 MB
missingok / notifemptyNo error if the file is missing; skip empty files
create 0640 user groupMake the new empty file with these permissions
postrotateTell the app to start writing to the new file
copytruncateCopy the file, then empty it in place (for apps that cannot reopen files)

After rotation you get app.log, app.log.1, app.log.2.gz and so on.

Test a rule without changing anything, then force a run:

sudo logrotate -d /etc/logrotate.d/orders     # dry run, shows what it would dosudo logrotate -f /etc/logrotate.d/orders     # force rotation now
OUTPUTterminalutf-8 · 2L

Why postrotate matters

The problem: after logrotate renames app.log to app.log.1, the app keeps writing into the same open file, which is now called app.log.1. The new app.log stays empty.

The fix: send the app a HUP signal (or restart it) so it opens the new app.log. If the app cannot do that, use copytruncate instead. It has a tiny risk of losing a few lines written during the copy.

Think of it like: swapping a full notebook for a new one. You must tell the writer to use the new notebook, or they keep writing in the old one.

Container logs

Docker saves everything a container prints to a file, and by default it never deletes them.

👉 Set limits on every Docker host, in /etc/docker/daemon.json:

{  "log-driver": "json-file",  "log-opts": { "max-size": "50m", "max-file": "5" }}
NORMALjsonutf-8 · 4L

This keeps at most 5 files of 50 MB per container.

In Kubernetes, apps should simply print logs to stdout and stderr. The kubelet rotates the files, and a log agent sends them on.

Central logging

Sending logs from every server to one central place.

Servers get replaced (and their logs go with them), and you need to search across all servers at once.

👉 As soon as you have more than a handful of servers.

App → stdout / file → Agent on each node → Central store → Search and dashboards
OUTPUTterminalutf-8 · 1L
AgentCommon destinations
Fluent BitLoki, Elasticsearch/OpenSearch, CloudWatch, S3
Promtail / Grafana AlloyLoki
FilebeatElasticsearch
CloudWatch agentAWS CloudWatch Logs
VectorAlmost anything

Good habits:

  • Structured (JSON) logs with fields like level, service and trace_id, so you can filter instead of grepping.
  • Never log secrets: passwords, tokens or full card numbers.
  • Keep logs as long as they are worth: debug logs for days, audit logs for a year or more (depending on rules your company must follow).
  • Add a request or trace ID so you can follow one request across many services.

You will build a full logging stack in the Monitoring and Observability course.

Real-world scenario: disk full from logs, again

du -sh /var/logls -lh /var/log
SHELLbashutf-8 · 2L

The app's log is 15 GB because nobody wrote a logrotate rule for it.

  1. Empty it to get space back now: : > file.
  2. Add the logrotate rule above, with maxsize.
  3. Test it with logrotate -d.
  4. Add a disk alert at 80%.

That fixes the cause, not just the symptom.

Common mistakes

  • No rotation rule for custom apps. The most common cause of full disks.
  • Rotating without postrotate or copytruncate, so the app keeps writing to the old file.
  • No limits on Docker logs for busy containers.
  • Logging secrets, which then get copied to a central system that many people can read.

Practice

  1. List the log files in /var/log with their sizes.
  2. Write a logrotate rule that keeps 7 compressed daily copies of /var/log/api/*.log, rotating early above 200 MB.
  3. Explain what delaycompress is for.
  4. Limit Docker logs to 3 files of 20 MB each.

Cheat sheet

CommandWhat it does
journalctl -p err -bErrors since boot
journalctl --vacuum-size=500MShrink the journal
logger "msg"Write to the system log
logrotate -d fileDry-run a rotation rule
logrotate -f fileForce rotation now
zgrep x file.gzSearch old, compressed logs

Key takeaways

  • Logs are the server's diary, and most live in /var/log.
  • Without rotation, logs grow until the disk is full.
  • logrotate renames, zips and deletes old logs on a schedule. Every app needs a rule.
  • After rotating, tell the app to write to the new file (postrotate).
  • Send logs to a central system, and never write secrets into logs.