Systemctl Service Logs Setup Using Logrotate
This guide explains how to set up log rotation for a service managed bysystemctl 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:
- Defines the service with
DescriptionandAfterdirectives. - 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, configurelogrotate:
-
Create a Logrotate Configuration File
Edit or create the logrotate configuration file for your service:
Add the following configuration: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:
Ensure the directory has appropriate permissions:Create the log file if it doesn’t exist:Restart the service to ensure it is writing logs:
-
Verify Logrotate Functionality
Check the logrotate status file to confirm that the log file is tracked:
Run
logrotatein verbose mode to see detailed output:Runlogrotatein debug mode to understand why it might not be working: -
Manually Trigger Log Rotation
Force a log rotation to test the setup:
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.
