Skip to main content

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:
This configuration:
  • Defines the service with Description and After 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:
  1. 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.
  2. 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:
  3. Verify Logrotate Functionality Check the logrotate status file to confirm that the log file is tracked:
    Run logrotate in verbose mode to see detailed output:
    Run logrotate in debug mode to understand why it might not be working:
  4. Manually Trigger Log Rotation Force a log rotation to test the setup:
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.