@@ -322,6 +322,13 @@ class Worker
322
322
*/
323
323
public static string $ logFile = '' ;
324
324
325
+ /**
326
+ * Log file maximum size in bytes, default 10M.
327
+ *
328
+ * @var int
329
+ */
330
+ public static int $ logFileMaxSize = 10_485_760 ;
331
+
325
332
/**
326
333
* Global event loop.
327
334
*
@@ -330,7 +337,7 @@ class Worker
330
337
public static ?EventInterface $ globalEvent = null ;
331
338
332
339
/**
333
- * Emitted when the master process get reload signal.
340
+ * Emitted when the master process gets a reload signal.
334
341
*
335
342
* @var ?callable
336
343
*/
@@ -2344,6 +2351,52 @@ public static function log(Stringable|string $msg, bool $decorated = false): voi
2344
2351
if (isset (static ::$ logFile )) {
2345
2352
$ pid = DIRECTORY_SEPARATOR === '/ ' ? posix_getpid () : 1 ;
2346
2353
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
+ }
2347
2400
}
2348
2401
}
2349
2402
0 commit comments