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 viapostrotate(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¬ifempty: 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?
- 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). - Configure Rotation Schedule & Retention:
- Rotation Frequency: Select
daily,weekly,monthly, oryearly. - 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).
- Rotation Frequency: Select
- Choose File Handling Method:
- Enable
copytruncatefor Node.js, PM2, Python, and daemon processes that keep file descriptors open. - Or configure
createwith octal file permissions (0640) and user/group ownership (www-data adm).
- Enable
- Select Compression & Options:
- Enable
compress(gzip) anddelaycompressfor safe background compression. - Enable
dateextto append timestamped-YYYYMMDDextensions to rotated archives.
- Enable
- 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:
- Crontab to Systemd Timer Generator: Convert traditional 5-field cron schedules into Systemd timers and service units.
- Rsync Command Generator: Generate dry-run verified rsync command lines with SSH port and key integration.
- NGINX Location Matcher: Test and debug NGINX URI prefix and regex match priority rules.
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
copytruncatewithcreateor misformattingpostrotatescripts). 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 -ForceLinux / 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/myappPython
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();
}
}
}