Linux Logrotate Config Generator & Validator

Generate production-grade /etc/logrotate.d/ configuration files for Node.js, PM2, NGINX, Docker, and PostgreSQL with dry-run verification commands.

Application Presets:
*Optional max log size threshold before forcing rotation
Rotation Directives & Flags:

How to Install Logrotate Configurations

1

Save Config File

Save the generated configuration into /etc/logrotate.d/your-app with root permissions.

2

Run Debug Dry-Run

Test with sudo logrotate -d /etc/logrotate.d/your-app to inspect rotation rules without deleting files.

3

Automatic Rotation

Logrotate is executed daily by the system cron daemon. No service restart or daemon reload is required.

Tool Options

copytruncate Support

Truncates active logs in-place without moving open file descriptors. Essential for Node.js, PM2, and Python apps.

Application Presets

Pre-configured templates for NGINX (with sharedscripts reload), PM2, Docker, and PostgreSQL databases.

Gzip & Date Extension

Automates gzip compression with delaycompress and produces clean date-stamped archive filenames (-%Y%m%d).

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the Linux Logrotate Config Generator & Validator do?

The Linux Logrotate Config Generator creates verified /etc/logrotate.d/ configuration files and dry-run debug commands for automated log rotation on Linux servers. It builds configuration rules for application logs (such as PM2, NGINX, Docker, and PostgreSQL), configures copytruncate to avoid closing open file descriptors, sets rotation frequencies (daily, weekly), controls compression and file retention limits, and prevents disk-full outages.

Core Concepts

Understanding log rotation directives prevents log loss and application crashes:

  • copytruncate: Copies the active log file to an archive filename and then truncates the original file in-place. This enables applications like Node.js, PM2, and Python daemons to continue writing logs without restarting or losing open file descriptors.
  • create [mode] [owner] [group]: Immediately creates a new empty log file after moving the old file. Ideal for services like NGINX that support signal reloading via postrotate (kill -USR1).
  • delaycompress: Defers compression of rotated logs until the next rotation cycle, preventing file corruption if an application or worker process is still writing closing log entries.
  • missingok & notifempty: Prevents logrotate from erroring out if a log file is absent, and skips creating empty archive files if no new logs were written during the interval.

How to use the tool?

  1. Select a Preset or Enter Custom Paths: Choose from built-in presets (PM2, NGINX, Docker, PostgreSQL) or enter your application log path pattern (e.g. /var/log/myapp/*.log).
  2. Configure Rotation Schedule & Retention:
    • Rotation Frequency: Select daily, weekly, monthly, or yearly.
    • Retention Count (rotate): Specify the maximum number of rotated archive files to keep before older logs are purged.
    • Size Threshold (maxsize / minsize): Force rotation when log files exceed a specific size threshold (e.g. 100M).
  3. Choose File Handling Method:
    • Enable copytruncate for Node.js, PM2, Python, and daemon processes that keep file descriptors open.
    • Or configure create with octal file permissions (0640) and user/group ownership (www-data adm).
  4. Select Compression & Options:
    • Enable compress (gzip) and delaycompress for safe background compression.
    • Enable dateext to append timestamped -YYYYMMDD extensions to rotated archives.
  5. Verify with Dry-Run Command: Copy and run the generated debug command (sudo logrotate -d /etc/logrotate.d/<config>) to simulate rotation before saving the configuration to disk.

Related Developer Utilities

If you are managing Linux servers, background services, or deployment automation, explore these complementary Blueutils utilities:

REST API Integration

Blueutils provides a free REST API endpoint (POST https://blueutils.com/api/linux/logrotate-generator) to programmatically generate production-ready /etc/logrotate.d/ configuration blocks and dry-run testing shell commands.

API Request Parameters

Name Type Description Example
logPath String Target log file path or glob pattern. "/var/log/nginx/*.log"
configName String Configuration file basename for /etc/logrotate.d/. "nginx"
frequency String Rotation interval (daily, weekly, monthly, yearly). "daily"
rotateCount Number Number of rotated archive files to retain. 14
copytruncate Boolean Whether to copy and truncate in-place without moving file descriptors. false
compress Boolean Whether to gzip compress rotated archives. true
delaycompress Boolean Whether to postpone compression until next cycle. true
missingok Boolean Whether to ignore missing log files without error. true
notifempty Boolean Whether to skip rotation if the log file is empty. true
dateext Boolean Whether to append date stamps (-YYYYMMDD) to archives. true
maxsize String Optional size limit to force rotation (e.g. 100M). "100M"
suUser String Optional user switch directive for permission sandboxes. "postgres"
suGroup String Optional group switch directive. "postgres"
postrotate String Shell script executed after rotation. "kill -USR1 \cat /var/run/nginx.pid`"`

API Request Payload Examples

cURL

curl -X POST https://blueutils.com/api/linux/logrotate-generator \
  -H "Content-Type: application/json" \
  -d '{
    "logPath": "/var/log/myapp/*.log",
    "configName": "myapp",
    "frequency": "daily",
    "rotateCount": 14,
    "copytruncate": true,
    "compress": true
  }'

Python

import requests

url = "https://blueutils.com/api/linux/logrotate-generator"
payload = {
    "logPath": "/var/log/myapp/*.log",
    "configName": "myapp",
    "frequency": "daily",
    "rotateCount": 14,
    "copytruncate": True,
    "compress": True
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = """
            {
                "logPath": "/var/log/myapp/*.log",
                "configName": "myapp",
                "frequency": "daily",
                "rotateCount": 14,
                "copytruncate": true,
                "compress": true
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/linux/logrotate-generator"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Indicates whether generation succeeded. true
configName String Normalized configuration filename. "myapp"
configOutput String Formatted text for the /etc/logrotate.d/ file. "/var/log/myapp/*.log {\n..."
debugCommands String Shell commands to save and test the configuration in debug mode. "sudo logrotate -d ..."

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "configName": "myapp",
  "logPath": "/var/log/myapp/*.log",
  "configOutput": "/var/log/myapp/*.log {\n    daily\n    rotate 14\n    missingok\n    notifempty\n    copytruncate\n    compress\n    delaycompress\n    dateext\n    dateformat -%Y%m%d\n}",
  "debugCommands": "# 1. Save config to /etc/logrotate.d/myapp\nsudo tee /etc/logrotate.d/myapp << 'EOF'\n/var/log/myapp/*.log {\n    daily\n    rotate 14\n    missingok\n    notifempty\n    copytruncate\n    compress\n    delaycompress\n    dateext\n    dateformat -%Y%m%d\n}\nEOF\n\n# 2. Test logrotate execution in dry-run/debug mode\nsudo logrotate -d /etc/logrotate.d/myapp"
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "Log path cannot be empty."
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to generate Logrotate configurations?

Integrating the Logrotate Generator API into provisioning scripts, Ansible playbooks, or autonomous deployment pipelines provides key advantages:

  • Rapid Script Validation: Enables developers and infrastructure engineers to quickly generate syntax-valid log rotation files tailored to specific software packages during server bootstrapping.
  • Optimized Token Efficiency for AI Agents: Offloading configuration formatting and permission directives to an external API significantly cuts prompt and completion token consumption for autonomous agents.
  • Deterministic Accuracy Without Hallucinations: Language models frequently hallucinate conflicting directives (such as mixing copytruncate with create or misformatting postrotate scripts). A dedicated API produces 100% deterministic, valid configurations every time.

Native Usage

How to verify and test logrotate configurations locally on Linux systems:

Windows (CMD / PowerShell)

Windows uses the Windows Event Log service rather than logrotate, but log maintenance can be scripted with PowerShell:

# Archive and purge log files older than 14 days
Get-ChildItem -Path "C:\logs\*.log" | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-14) } | Remove-Item -Force

Linux / Unix (Bash)

# 1. Test logrotate configuration in dry-run debug mode (does not alter files)
sudo logrotate -d /etc/logrotate.d/myapp

# 2. Force immediate manual rotation for testing
sudo logrotate -f /etc/logrotate.d/myapp

Python

Using Python standard library logging.handlers.RotatingFileHandler for in-application rotation:

import logging
from logging.handlers import RotatingFileHandler

# Rotate when file reaches 10MB, keep 5 backup archives
handler = RotatingFileHandler("app.log", maxBytes=10*1024*1024, backupCount=5)
logger = logging.getLogger("AppLogger")
logger.setLevel(logging.INFO)
logger.addHandler(handler)

logger.info("Application started with automatic local file rotation.")

Java

Using standard Java runtime to inspect or invoke logrotate:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class LogrotateTester {
    public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder("sudo", "logrotate", "-d", "/etc/logrotate.d/myapp");
        pb.redirectErrorStream(true);

        try {
            Process process = pb.start();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }
            int exitCode = process.waitFor();
            System.out.println("Dry-run test exit code: " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Frequently Asked Questions (FAQ)

What does copytruncate do in logrotate?

copytruncate copies the active log file to an archive and then truncates the original in-place. This allows applications like Node.js, PM2, and Python to continue logging without closing their open file descriptors.

How do I test my logrotate configuration safely?

Run sudo logrotate -d /etc/logrotate.d/your-config in debug dry-run mode. This prints the exact actions logrotate will take without modifying, rotating, or deleting any files.

Do I need to restart logrotate after creating a config?

No. Logrotate is not a long-running daemon; it is executed as a daily cron job or systemd timer (logrotate.timer). Simply saving your file into /etc/logrotate.d/ is sufficient.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.