PHP

Rotating Log Writer

admin by @admin ADMIN
7m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Append to a single log file but auto-rotate to .1/.2/.3 once the file exceeds a configurable size. No external dependencies — just rename + size check.
PHP
Raw
<?php
function rotatingLog(string $path, string $line, int $maxBytes = 5_000_000, int $keep = 3): void {
    if (is_file($path) && filesize($path) >= $maxBytes) {
        for ($i = $keep; $i > 1; $i--) {
            $older = "$path." . ($i - 1);
            if (is_file($older)) rename($older, "$path.$i");
        }
        rename($path, "$path.1");
    }
    file_put_contents($path, $line . PHP_EOL, FILE_APPEND | LOCK_EX);
}

rotatingLog('/var/log/myapp.log', '[' . date('c') . '] something happened');
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.