Skip to content

Commit 36700b8

Browse files
authored
Merge pull request #1105 from akotulu/master
Implemented max log file size with truncation.
2 parents 92021a7 + 85405c6 commit 36700b8

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

src/Worker.php

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,13 @@ class Worker
322322
*/
323323
public static string $logFile = '';
324324

325+
/**
326+
* Log file maximum size in bytes, default 10M.
327+
*
328+
* @var int
329+
*/
330+
public static int $logFileMaxSize = 10_485_760;
331+
325332
/**
326333
* Global event loop.
327334
*
@@ -330,7 +337,7 @@ class Worker
330337
public static ?EventInterface $globalEvent = null;
331338

332339
/**
333-
* Emitted when the master process get reload signal.
340+
* Emitted when the master process gets a reload signal.
334341
*
335342
* @var ?callable
336343
*/
@@ -2344,6 +2351,52 @@ public static function log(Stringable|string $msg, bool $decorated = false): voi
23442351
if (isset(static::$logFile)) {
23452352
$pid = DIRECTORY_SEPARATOR === '/' ? posix_getpid() : 1;
23462353
file_put_contents(static::$logFile, sprintf("%s pid:%d %s\n", date('Y-m-d H:i:s'), $pid, $msg), FILE_APPEND | LOCK_EX);
2354+
2355+
// Check the file size and truncate if it exceeds max size
2356+
if (!empty(static::$logFileMaxSize) && ($fileSize = filesize(static::$logFile)) > static::$logFileMaxSize) {
2357+
// Open files
2358+
$source = fopen(static::$logFile, 'r');
2359+
2360+
if (!$source) {
2361+
return;
2362+
} else if (!flock($source, LOCK_EX)) {
2363+
fclose($source);
2364+
return;
2365+
}
2366+
2367+
$newFile = static::$logFile . '.tmp';
2368+
$destination = fopen($newFile, 'w');
2369+
2370+
if (!$destination) {
2371+
flock($source, LOCK_UN);
2372+
fclose($source);
2373+
return;
2374+
}
2375+
2376+
// Move to the halfway point in the source file
2377+
$halfwayPoint = (int)($fileSize / 2);
2378+
fseek($source, $halfwayPoint);
2379+
2380+
// Find the next newline character to ensure we don't cut in the middle of a line
2381+
while (($char = fgetc($source)) !== false) {
2382+
if ($char === "\n") {
2383+
break;
2384+
}
2385+
}
2386+
2387+
// Copy the second half into the new file
2388+
while (!feof($source)) {
2389+
fwrite($destination, fread($source, 8192)); // Read and write 8KB chunks
2390+
}
2391+
2392+
// Replace the old file with the new truncated file
2393+
rename($newFile, static::$logFile);
2394+
2395+
// Close both files
2396+
flock($source, LOCK_UN);
2397+
fclose($source);
2398+
fclose($destination);
2399+
}
23472400
}
23482401
}
23492402

0 commit comments

Comments
 (0)