Linux & Servers guides, explanations and reader checklists on whilenetworking.com

Setting Up Automated Log Analysis with Logrotate and rsyslog

In the realm of Linux server administration, log management is often treated as an afterthought until a security incident occurs or disk space fills up…

In the realm of Linux server administration, log management is often treated as an afterthought until a security incident occurs or disk space fills up unexpectedly. However, effective log analysis relies on two fundamental components: capturing logs efficiently and rotating them to maintain system health. This guide details how to configure rsyslog for centralized logging and logrotate for automated file management, creating a robust foundation for your server’s observability.

Understanding the Core Components

Before diving into configuration, it is essential to understand the roles of these two tools. rsyslog (Remote Syslog) is the standard logging daemon used by most Linux distributions. Its primary function is to collect log messages from the system and services, filter them based on rules, and route them to specific destinations such as local files, remote servers, or external analysis platforms.

logrotate, on the other hand, is a utility designed to manage log file sizes. It compresses old logs, moves them to archive directories, and rotates them periodically. Without logrotate, log files can grow indefinitely, eventually consuming all available disk space and causing services like web servers or databases to crash due to lack of write permissions on full disks.

Configuring rsyslog for Centralized Collection

The first step in automated analysis is ensuring that logs are being captured and routed correctly. By default, rsyslog often sends logs only to /var/log/messages. To enable granular analysis, you need to edit the configuration file, typically located at /etc/rsyslog.conf or within files under /etc/rsyslog.d/.

Defining Custom Filters

You can create specific rules to separate logs by service or severity. For example, you might want all auth.log entries (security-related) to be sent to a dedicated file while keeping general system messages in their default location.

Add the following rule to your configuration:

:programname, isequal, "sshd" /var/log/auth-sshd.log & stop
& ~

This command tells rsyslog to intercept any message where the program name matches “sshd” and route it to /var/log/auth-sshd.log. The & stop prevents further processing of that specific message, and & ~ discards duplicates if multiple rules match.

Enabling Remote Forwarding

For true analysis, logs often need to leave the local machine. To enable remote forwarding, ensure the imuxsock.c module is loaded in /etc/rsyslog.conf. Then, configure a remote receiver (like a SIEM or a central logging server) by adding a rule such as:

:msgtype, isequal, "SYSLOG" action(type="omfwd" target="remote-server-ip" template="RSYSLOG_SyslogTemplate")

Note: Ensure your firewall allows traffic on UDP port 514 or TCP port 514 before enabling this feature.

Mastering Logrotate for Disk Space Management

Once logs are being generated, they must be managed. logrotate is configured via a file located at /etc/logrotate.conf, but the actual rules for specific services usually reside in files within /etc/logrotate.d/. A common mistake is setting rotation frequencies that are too aggressive, leading to log fragmentation and performance issues, or too sparse, causing disk exhaustion.

Setting Rotation Frequency and Compression

A standard configuration for a web server log like access.log might look like this:

/var/log/nginx/access.log {
    daily
    missingok
    rotate 7
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        /usr/sbin/nginx -s reload > /dev/null
    endscript
}

Here, daily rotates logs every day. rotate 7 keeps seven compressed archives (approximately one month of daily logs). compress applies gzip compression to old files to save space. The delaycompress option ensures the most recent rotated file is not compressed immediately, allowing debugging if needed.

The postrotate script is crucial for services that do not reopen log files automatically upon rotation. For Nginx or Apache, reloading the service ensures new logs are written to the newly created empty file rather than appending to the old one.

Integrating Log Analysis with External Tools

Automated analysis becomes powerful when combined with external tools. Once rsyslog is routing data and logrotate is managing storage, you can forward logs to platforms like ELK Stack (Elasticsearch, Logstash, Kibana) or the Graylog server.

To prepare for this integration, ensure your log paths defined in rsyslog match the input plugins of your analysis tool. For instance, if you are using Fluentd or Filebeat, configure them to tail the specific files created by logrotate. Be aware that logrotate changes the inode number when it rotates a file; if your monitoring agent is not configured to handle this, it may miss events during the rotation window.

Handling Security Logs Separately

Security logs require special attention. They should be rotated less frequently or kept uncompressed for shorter periods to ensure immediate availability for forensic analysis. Consider creating a dedicated partition for security logs on /var/log/security and configuring logrotate to rotate these files weekly rather than daily, but retaining them for 90 days instead of 7.

Common Pitfalls and Troubleshooting

Even with careful configuration, issues can arise. One frequent error is the “Permission Denied” issue where logrotate cannot create new files because the user context has changed. Always use the create directive in your logrotate config to explicitly define the ownership and permissions of the new log file.

Another common problem involves the postrotate script failing silently. If the reload command fails, the service continues writing to the old (now empty or rotated) file, breaking your analysis pipeline. Always check the exit status of scripts within logrotate. You can add error handling like || true if the reload is non-critical, but for security logs, you might want to ensure the reload succeeds before continuing.

Practical Checklist for Deployment

Before finalizing your setup, run through this checklist to ensure a stable environment:

  1. Backup Configuration: Always backup /etc/rsyslog.conf, /etc/logrotate.conf, and files in /etc/rsyslog.d/ and /etc/logrotate.d/.
  2. Test Rules Syntax: Use rsyslogd -N1 to check for configuration errors without starting the daemon. Similarly, run logrotate -d /etc/logrotate.conf in debug mode to see what actions would be taken without actually rotating files.
  3. Verify Permissions: Ensure the directories /var/log and subdirectories are owned by root:adm or the appropriate group with correct permissions (usually 755 for directories, 640 for logs).
  4. Monitor Disk Usage: Set up a cron job to alert you if disk usage on /var/log exceeds 80%.
  5. Validate Remote Connectivity: If forwarding logs remotely, test connectivity from the server to the destination IP/Port using telnet or nc.
  6. Review Compression Ratios: After rotating a few times, check the size of compressed files to ensure compression is effective. If ratios are poor (e.g., text logs that don’t compress well), consider adjusting retention policies.

Conclusion

Setting up automated log analysis with logrotate and rsyslog transforms your Linux server from a black box into an observable system. By configuring rsyslog to route specific streams of data and using logrotate to maintain disk health, you create a sustainable logging infrastructure. Remember that while these tools are powerful, the specific configuration must align with your organization’s compliance requirements, security policies, and available storage. Always test your configurations in a non-production environment before applying them to critical servers.