Log files are the most honest record of what your infrastructure is actually doing, but they are also one of the fastest ways to run out of disk and fail an audit. Early in my career I watched a single verbose Java service fill a 200GB production volume in under 36 hours because no log rotation was configured. The service crashed, the database that shared the volume corrupted, and we spent a weekend restoring from backups. That incident taught me that log rotation and retention are not housekeeping tasks you get to later; they are core operational controls. For teams new to running production systems, understanding how to rotate logs safely, define a defensible retention policy, and apply storage optimization will save you from outages, runaway costs, and painful compliance conversations.
Why Unbounded Logs Will Fill Disks and Break Audit Trails
Every process that writes to stdout, a file in /var/log, or a container log driver is creating data that never stops growing unless you tell it to. On a typical Linux host running Nginx, a Java application, and systemd-journald, you can easily generate 5-15GB per day even with moderate traffic. Without rotation, that growth is linear and unbounded. In my experience, the first symptom is rarely a monitoring alert. It is slow I/O as the filesystem hits 85-90% capacity, followed by failed deployments, failed health checks, and eventually a read-only filesystem.
Beyond availability, retention is a compliance requirement. Most frameworks do not tell you to keep logs forever; they tell you to keep them long enough, securely, and to be able to prove you did. PCI DSS requires at least one year of audit logs with three months immediately available. HIPAA expects six years of audit trails. SOC 2 asks for evidence that your retention policy is documented and enforced. If you delete too early you fail an audit. If you keep everything forever on expensive hot storage, you waste budget and slow down search.
The goal is not just to delete old files. A good strategy addresses three questions: how to break active logs into manageable files without losing data or interrupting the application, how long to keep each tier of logs, and where to store them at the lowest cost that still meets access requirements. When you solve those three together, storage optimization becomes a natural outcome rather than a separate project.
How Fast Logs Grow in Real Environments
To estimate growth, sample a production host for 24 hours and measure. I typically run du -sh /var/log/* and journalctl --disk-usage at the start and end of a business day. For containerized workloads, check docker system df and inspect /var/lib/docker/containers/*/*.log or /var/log/pods on Kubernetes nodes. You will often find that access logs dominate volume but application debug logs dominate inode count. Both matter, because millions of small rotated files can exhaust inodes before you exhaust bytes.
Configuring logrotate for Linux Hosts and Systemd Services
On almost every Debian, RHEL, or Ubuntu host, logrotate is already installed and runs daily via cron or a systemd timer. It is still the most reliable tool for file-based log rotation, and I continue to use it for anything that writes directly to a file, from Nginx to custom application logs to syslog. The key is to configure it explicitly for your application rather than relying on the default policy, which often only rotates weekly and keeps four copies.
A rotation policy is defined by frequency, size threshold, retention count, and post-rotation action. Frequency handles time-based rotation, size prevents a runaway process from filling disk between runs, retention defines how many archives to keep locally, and the post-rotate script tells the application to reopen its log handle. Forgetting that last part is a common beginner mistake. If you rotate the file but do not signal the process, it will keep writing to the deleted file descriptor and you will see disk space that never frees until restart.
# /etc/logrotate.d/myapp - Production config for a verbose API service
/var/log/myapp/*.log {
daily
rotate 14
size 250M
compress
delaycompress
missingok
notifempty
create 0640 appuser adm
sharedscripts
postrotate
# Send USR1 to reopen logs, or reload if USR1 is not supported
if [ -f /run/myapp.pid ]; then
kill -USR1 $(cat /run/myapp.pid) 2>/dev/null || true
fi
# Alternative for services that need reload
# systemctl reload myapp > /dev/null 2>&1 || true
endscript
}
This configuration does several things that I have found essential in production. It rotates daily but also if the file exceeds 250MB, which protects against traffic spikes. It keeps 14 compressed archives, giving us two weeks of local history for rapid troubleshooting without needing to fetch from central storage. delaycompress leaves the most recent rotated file uncompressed so tools like grep can read it without decompressing. create 0640 ensures the new file has correct permissions immediately, which prevents the application from failing to write after rotation.
Validating and Testing Without Waiting Days
Never wait for the daily cron to test your config. Run logrotate -d /etc/logrotate.d/myapp for a debug dry-run that shows what would happen without making changes. Then run logrotate -f /etc/logrotate.d/myapp to force a rotation and verify that the application reopened its file handle. Check with lsof | grep myapp.log to confirm the process is writing to the new inode. For systemd-journald, which does not use logrotate, tune /etc/systemd/journald.conf with SystemMaxUse=2G and MaxRetentionSec=14day and then restart journald. The Docker Documentation and systemd docs are worth reading closely here, because default values vary significantly between distributions.
Containing Log Growth in Docker and Kubernetes Clusters
Containers introduce a different problem. By default, Docker's json-file logging driver writes a single JSON file per container and never rotates it unless you configure it. I have seen Kubernetes nodes go NotReady because a single pod with verbose logging filled the kubelet's disk with a 40GB container log. On Kubernetes, log rotation is not centrally enforced by the control plane; it is delegated to the kubelet and the container runtime configuration.
For standalone Docker hosts, set global defaults in daemon.json so every new container inherits sane limits. For Kubernetes, configure the kubelet's containerLogMaxSize and containerLogMaxFiles flags. This is documented in the Kubernetes Documentation under kubelet configuration, and it is one of the first settings I tune on any new cluster.
// /etc/docker/daemon.json - Enforce rotation for all containers
{
"log-driver": "json-file",
"log-opts": {
"max-size": "50m",
"max-file": "5",
"compress": "true",
"labels": "service,environment",
"env": "APP_VERSION"
}
}
// kubelet config snippet (in /var/lib/kubelet/config.yaml)
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
containerLogMaxSize: 50Mi
containerLogMaxFiles: 5
With these settings, each container keeps at most five 50MB files, for a maximum of 250MB per container. When the sixth file would be created, the oldest is deleted. Compression reduces that footprint further. This is local node retention only; it is not your long-term retention policy. For anything you need to keep beyond a few days, you must ship logs to a centralized system before they are rotated away. If you are running at scale, pairing this with an architecture like ELK Stack Architecture: Elasticsearch, Logstash and Kibana at Scale gives you a durable, searchable backend where retention can be managed with Index Lifecycle Management instead of on-node files.
Choosing Between json-file, journald and Log Drivers
Docker also supports journald, syslog, and local drivers. The local driver is more performant than json-file and handles compression internally, which I now prefer for high-throughput services. Avoid logging directly to syslog from containers unless you have a clear reason, as it couples container lifecycle to the host's syslog availability. Whatever driver you choose, define it declaratively and do not allow developers to override max-size per container without review.
Designing Retention Policies That Satisfy Cost Targets and Compliance Audits
A retention policy answers how long you keep different classes of logs and where. The mistake I see most often is applying a single retention number to everything. Access logs, application logs, audit logs, and security logs have different value and different regulatory requirements. You can and should retain them differently.
Start by classifying logs. For a typical web platform, I use four classes: 1) Operational application logs needed for debugging, 2) Web access logs, 3) Security and authentication audit logs, and 4) Infrastructure and Kubernetes audit logs. Operational logs are valuable for about 14-30 days, after which their debugging value drops sharply. Access logs may be needed for 30-90 days for traffic analysis. Security and audit logs are where compliance matters most and may require 1-7 years. Once classified, map each class to a tier: hot storage for immediate search, warm storage for occasional investigation, and cold or archival storage for compliance holds.
Document the policy in a short, auditable table that your team and auditors can read. Include the retention period, storage tier, encryption requirement, and legal justification. I've found that having this table in your runbook prevents ad-hoc decisions to delete logs to free space under pressure.
| Log Class | Hot Retention (Searchable) | Warm / Cold Retention | Justification |
|---|---|---|---|
| Application Debug Logs | 14 days in Elasticsearch / Loki | 30 days in S3 Standard-IA, then delete | Debugging window; low compliance value |
| Web Access Logs | 30 days | 90 days in S3 Glacier Instant | Traffic analysis + incident response |
| Auth & Security Audit | 90 days | 1 year hot, 6 years in Glacier Deep Archive | PCI DSS, SOC 2, HIPAA requirements |
| Kubernetes API Audit | 30 days | 1 year in immutable bucket | Forensics and change tracking |
When you implement the policy, enforce immutability for audit classes. In AWS S3 this means Object Lock with compliance mode. In Elasticsearch this means index lifecycle policies that do not allow deletion before the retention date and that roll over based on size and age. A written policy that is not enforced by the storage system will not survive an audit.
Storage Optimization Techniques: Compression, Tiering and Structured Payloads
Retention duration drives cost, but storage optimization determines how much each retained day actually costs. There are three levers I rely on: reducing log volume at the source, compressing efficiently, and tiering storage based on access patterns. Used together, they can reduce log storage costs by 70-85% without losing information you need.
First, reduce noise at the source. Most applications log at INFO or DEBUG in development but should run at WARN or INFO with sampling in production. Health check endpoints, in particular, can generate thousands of lines per minute that have zero diagnostic value. Filter them before they are ever written. Structured logging helps here enormously. When logs are emitted as JSON with consistent fields, you can drop or sample fields at the collector rather than storing everything as raw text. If you have not standardized this yet, read Structured Logging: JSON Format, Context Fields and Log Aggregation before you invest in more storage.
Second, compress aggressively but intelligently. gzip with default level 6 gives you about 80-90% reduction on text logs and is universally readable. zstd offers better performance and similar ratio and is now supported by most modern log shippers. On hosts using logrotate, compress with compresscmd /usr/bin/zstd is a simple win. For centralized storage, columnar formats like Parquet combined with zstd can reduce long-term S3 costs even further.
Third, tier storage. Do not keep a year of logs in Elasticsearch if you only search the last 14 days. A common pattern I deploy is to keep 14 days in Elasticsearch or Grafana Loki for fast queries, 30-90 days in S3 Standard-IA for rehydration if needed, and beyond that in Glacier Deep Archive for compliance. Lifecycle rules automate the transition so you do not pay hot storage prices for cold data.
# Terraform - S3 lifecycle for tiered log storage optimization
resource "aws_s3_bucket_lifecycle_configuration" "app_logs" {
bucket = aws_s3_bucket.app_logs.id
rule {
id = "tier-and-expire-app-logs"
status = "Enabled"
filter { prefix = "app/" }
transition {
days = 30
storage_class = "STANDARD_IA"
}
transition {
days = 90
storage_class = "GLACIER"
}
expiration {
days = 365
}
}
rule {
id = "retain-audit-logs-immutable"
status = "Enabled"
filter { prefix = "audit/" }
transition {
days = 90
storage_class = "GLACIER"
}
# No expiration - retained 6 years via Object Lock compliance mode
}
}
# Elasticsearch ILM policy - keep hot for 14 days, then warm, delete after 30
# Applied via the ILM API or Terraform elasticstack provider
Monitor the effectiveness of these optimizations with metrics, not assumptions. Track log_bytes_written_per_day, compressed_ratio, and storage_cost_per_gb_month in your monitoring system. If you already use Prometheus and Alertmanager: Complete Setup for Production Monitoring, you can expose filesystem usage and S3 bucket size as metrics and alert when growth exceeds your retention model forecast. In my experience, a simple alert on predict_linear(node_filesystem_avail_bytes[6h], 24*3600) < 0 has caught rotation failures before disks filled.
Automating Retention Enforcement with Infrastructure-as-Code and Centralized Aggregation
Manual retention does not work. Someone will forget to run a cleanup script, or a new service will be deployed without configuration and will silently accumulate logs until it causes an incident. The only reliable approach is to enforce rotation and retention declaratively through infrastructure-as-code and through your centralized logging platform.
For host-level logs, manage logrotate configs, journald.conf, Docker daemon.json, and kubelet flags via Ansible, Puppet, or Terraform cloud-init templates. Version them in Git and apply them on every host build. For cloud storage, define S3 or GCS lifecycle policies in Terraform as shown above so they are reviewable and auditable. For your logging stack, define retention in code as well. In ELK, that means Index Lifecycle Policies. In Loki, that means compactor.retention_enabled and limits_config.retention_period. In both cases, test the policies in a staging environment by ingesting data, advancing the index date, and confirming transitions happen.
Equally important is monitoring that enforcement is working. I recommend two checks: a daily job that lists buckets or indices with non-compliant retention settings, and an alert that fires if any host's /var/log usage exceeds 70% for more than an hour. The second alert often indicates that rotation failed, perhaps because an application did not handle the postrotate signal. When that happens, your runbook should tell the on-call engineer to check systemctl status logrotate.timer, inspect the application's file descriptors, and restart the service if needed. Automation reduces toil, but only if you also automate the verification that it worked.
Finally, treat retention enforcement as part of your deployment checklist. When a new service is onboarded, ask three questions: where does it log, how is it rotated, and what retention class does it belong to. If the answers are not documented and implemented before the service goes live, you are accumulating technical debt that will be paid in storage costs or audit findings.
Frequently Asked Questions
How often should log rotation run for high-traffic services?
For most services, daily rotation is sufficient. For high-traffic services that generate more than 500MB per day, add a size threshold like size 250M so rotation triggers multiple times per day if needed. I usually combine both: daily plus size-based, which protects against unexpected spikes without creating thousands of tiny files during quiet periods.
Is it safe to delete rotated logs manually to free disk in an emergency?
You can delete compressed archives in /var/log if you have already shipped them to central storage, but never delete the active log file that the process is writing to. Deleting an open file does not free space until the process closes the handle. Instead, truncate it with : > /var/log/myapp/app.log or truncate -s 0 /var/log/myapp/app.log and then fix the rotation config so the issue does not recur.
What retention period should I start with if compliance requirements are unclear?
Start with 30 days searchable hot retention and 90 days in warm/cold storage for general application logs, and 1 year for any authentication or audit logs. Document this as your default retention policy and get explicit sign-off from your security or compliance owner. It is much easier to extend retention later than to explain why logs were deleted too early. Always keep the policy documented in Git and enforced by lifecycle rules rather than manual deletion.
How does log rotation differ from log retention?
Log rotation breaks a growing log file into smaller, time- or size-bounded files and optionally compresses them. It controls file size and keeps the active file manageable. Log retention defines how long you keep those rotated files, both locally and in centralized storage, and when they are deleted or moved to cheaper tiers. You need both: rotation without retention will still fill disk eventually, and retention without rotation will leave you with a single huge file that is hard to search or ship.