php
53 lines · 9 steps
How a rotating file logger works in PHP
A logger that caps each file's size and shifts old logs into numbered archives, pruning the excess.
Explained by
highlit
1<?php
2
3final class RotatingFileLogger
4{
5 private const MAX_BYTES = 5 * 1024 * 1024;
6 private const MAX_FILES = 5;
7
8 public function __construct(private readonly string $path)
9 {
10 }
11
12 public function write(string $message): void
13 {
14 $this->rotateIfNeeded();
15
16 $line = sprintf('[%s] %s%s', date('Y-m-d H:i:s'), $message, PHP_EOL);
17 file_put_contents($this->path, $line, FILE_APPEND | LOCK_EX);
18 }
19
20 private function rotateIfNeeded(): void
21 {
22 if (!is_file($this->path) || filesize($this->path) < self::MAX_BYTES) {
23 return;
24 }
25
26 $oldest = sprintf('%s.%d', $this->path, self::MAX_FILES);
27 if (is_file($oldest)) {
28 unlink($oldest);
29 }
30
31 for ($i = self::MAX_FILES - 1; $i >= 1; $i--) {
32 $source = sprintf('%s.%d', $this->path, $i);
33 if (is_file($source)) {
34 rename($source, sprintf('%s.%d', $this->path, $i + 1));
35 }
36 }
37
38 rename($this->path, $this->path . '.1');
39
40 $this->pruneByCount();
41 }
42
43 private function pruneByCount(): void
44 {
45 $archives = glob($this->path . '.*') ?: [];
46
47 usort($archives, static fn (string $a, string $b): int => filemtime($b) <=> filemtime($a));
48
49 foreach (array_slice($archives, self::MAX_FILES) as $stale) {
50 @unlink($stale);
51 }
52 }
53}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Rotation keeps log files bounded by size and count so disk usage never grows without limit.
- 2Renaming files in reverse index order avoids clobbering an archive before it has been shifted.
- 3LOCK_EX on appends guards against interleaved writes when multiple processes log concurrently.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
php
class TwoFactorController extends Controller { public function show(Request $request): View|RedirectResponse {
Two-factor auth challenge flow in Laravel
authentication
two-factor
middleware
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-rotating-file-logger-works-in-php-explained-php-e078/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.