Log Rotation Setup

Creates and configures log rotation rules for custom applications.

Published: April 20, 2024

Detailed Information

This script creates and configures log rotation rules for custom applications. Log rotation prevents log files from growing too large and preserves disk space.

What Does This Script Do?

This script automates log rotation configuration:

  • Creates log rotation rule
  • Sets rotation frequency (daily/weekly/monthly)
  • Sets number of rotations to keep
  • Configures compression settings
  • Adds service reload command

Why Should You Use It?

Log rotation is critical for disk management:

  • Disk Savings: Automatically cleans old logs
  • Performance: Prevents large log files
  • Organization: Keeps log files organized

How to Use

Step-by-Step Usage Guide

1. Run Script

sudo chmod +x logrotate_setup.sh
sudo ./logrotate_setup.sh

2. Answer Questions

The script will ask you:

  • Application name
  • Log file path
  • Rotation frequency (daily/weekly/monthly)
  • Number of rotations to keep

3. Test Configuration

sudo logrotate -d /etc/logrotate.d/

Requirements

Requirements

  • Root Privileges: Script must be run as root
  • logrotate: Usually installed by default

Use Cases

Use Cases

1. Custom Application Logs

Configure log rotation for your custom applications.

2. Disk Management

Keep log file disk space under control.

Examples

Usage Examples

Example 1: Basic Usage

sudo ./logrotate_setup.sh
# App name: myapp
# Log path: /var/log/myapp/app.log
# Frequency: daily
# Keep: 7

Code

#!/bin/bash

# Log Rotation Configuration Script

if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root"
    exit 1
fi

read -p "Enter application name: " APP_NAME
read -p "Enter log file path: " LOG_PATH
read -p "Rotation frequency (daily/weekly/monthly) [daily]: " FREQUENCY
FREQUENCY=${FREQUENCY:-daily}
read -p "Keep how many rotations [7]: " KEEP
KEEP=${KEEP:-7}

cat > "/etc/logrotate.d/$APP_NAME" << EOF
$LOG_PATH {
    $FREQUENCY
    rotate $KEEP
    compress
    delaycompress
    missingok
    notifempty
    create 0644 www-data www-data
    sharedscripts
    postrotate
        systemctl reload $APP_NAME > /dev/null 2>&1 || true
    endscript
}
EOF

echo "✓ Log rotation configured for $APP_NAME"
echo ""
echo "Config file: /etc/logrotate.d/$APP_NAME"
echo ""
echo "Test configuration:"
echo "logrotate -d /etc/logrotate.d/$APP_NAME"
echo ""
echo "Force rotation:"
echo "logrotate -f /etc/logrotate.d/$APP_NAME"

Usage

sudo chmod +x logrotate_setup.sh
sudo ./logrotate_setup.sh

# Test configuration
sudo logrotate -d /etc/logrotate.d/<app_name>

Troubleshooting

Troubleshooting

Problem: Log rotation not working

Solution: Test configuration:

sudo logrotate -d /etc/logrotate.d/

Tags

logrotate log management log rotation disk management