Systemctl Service Logs Setup Using Logrotate
This guide explains how to set up log rotation for a service managed by systemctl
using logrotate
.
Service Setup in systemctl
First, create a systemctl
service configuration for your application. Below is an example configuration file for a service named app
:
[Unit]
Description=app
After=network.target
[Service]
Type=simple
User=ubuntu
Group=ubuntu
StandardOutput=append:/var/log/app/app.log
StandardError=append:/var/log/app/app.log
WorkingDirectory=/var/www/app
ExecStart=/var/www/app/main
Restart=always
[Install]
WantedBy=multi-user.target
This configuration:
- Defines the service with
Description
andAfter
directives. - Redirects standard output and error to
/var/log/app/app.log
. - Sets the working directory and the command to start the service.
- Configures the service to always restart if it fails.
Log Rotation Setup
To manage log rotation for the service logs, configure logrotate
:
-
Create a Logrotate Configuration File
Edit or create the logrotate configuration file for your service:
sudo nano /etc/logrotate.d/app
Add the following configuration:
/var/log/app/app.log { daily missingok rotate 7 compress delaycompress notifempty create 0640 root root sharedscripts postrotate systemctl reload app.service > /dev/null 2>&1 || true endscript }
This configuration:
- Rotates the log file daily.
- Keeps 7 rotated log files before deleting the oldest.
- Compresses old logs.
- Skips empty logs.
- Creates new log files with specific permissions and ownership.
- Runs a script to reload the service after rotation.
-
Prepare Log File and Directory
Ensure the log file and directory have the correct permissions:
sudo chmod 644 /var/log/app/app.log sudo chown root:root /var/log/app/app.log
Ensure the directory has appropriate permissions:
sudo chmod 755 /var/log/app/
Create the log file if it doesn't exist:
sudo touch /var/log/app/app.log
Restart the service to ensure it is writing logs:
sudo systemctl restart app.service
-
Verify Logrotate Functionality
Check the logrotate status file to confirm that the log file is tracked:
cat /var/lib/logrotate/status
Run
logrotate
in verbose mode to see detailed output:sudo logrotate -v /etc/logrotate.d/app
Run
logrotate
in debug mode to understand why it might not be working:sudo logrotate -d /etc/logrotate.d/app
-
Manually Trigger Log Rotation
Force a log rotation to test the setup:
sudo logrotate -f /etc/logrotate.d/app
By following these steps, you will set up log rotation for your service logs, ensuring they are managed and rotated daily.
This document provides a complete setup for managing and rotating logs for a service using
logrotate
. Adjust the paths and filenames according to your specific requirements.