Skip to content

Commit 0dbf962

Browse files
committed
refactor: replace error_log with Yii logger
Replace error_log() calls with Yii::error() for better log management and consistency. Keep error_log() in critical paths (logging system itself, shutdown handlers) to avoid recursion and ensure messages are captured when Yii is unavailable. Changes: - Use Yii::error() for connection pool errors - Use Yii::error() for component cleanup errors - Remove redundant debug error_log() in queue worker - Add clear comments explaining remaining error_log() usage
1 parent 2fa73f0 commit 0dbf962

File tree

9 files changed

+31
-15
lines changed

9 files changed

+31
-15
lines changed

src/Coroutine/CoroutineApplication.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,15 +119,15 @@ public function resetCoroutineContext(): void
119119
try {
120120
$store['db']->close();
121121
} catch (\Throwable $e) {
122-
error_log("[CoroutineApplication] Error closing db: " . $e->getMessage());
122+
\Yii::error('Error closing db: ' . $e->getMessage(), __CLASS__);
123123
}
124124
}
125125

126126
if (isset($store['redis']) && is_object($store['redis']) && method_exists($store['redis'], 'close')) {
127127
try {
128128
$store['redis']->close();
129129
} catch (\Throwable $e) {
130-
error_log("[CoroutineApplication] Error closing redis: " . $e->getMessage());
130+
\Yii::error('Error closing redis: ' . $e->getMessage(), __CLASS__);
131131
}
132132
}
133133

src/Db/CoroutineDbConnection.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ public function close(): void
7474
try {
7575
$this->ensurePool()->release($pdo);
7676
} catch (\Throwable $e) {
77-
error_log('[CoroutineDbConnection] Error releasing connection to pool: ' . $e->getMessage());
77+
\Yii::error('Error releasing connection to pool: ' . $e->getMessage(), __CLASS__);
7878
}
7979
} else {
8080
parent::close();
@@ -208,7 +208,7 @@ private static function registerShutdownHandler(): void
208208
try {
209209
self::shutdownAllPools();
210210
} catch (\Throwable $e) {
211-
// Silently handle errors during shutdown handler
211+
// Use error_log here to avoid dependency on Yii during shutdown
212212
error_log('[CoroutineDbConnection] Error in shutdown handler: ' . $e->getMessage());
213213
}
214214
}

src/Log/CoroutineFileTarget.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,7 @@ private function writeFormattedMessages(array $formattedMessages): void
138138
}
139139

140140
if (($fp = @fopen($this->logFile, 'a')) === false) {
141+
// Use error_log here to avoid recursion in logging system
141142
error_log("Unable to append to log file: {$this->logFile}");
142143
return;
143144
}
@@ -150,6 +151,7 @@ private function writeFormattedMessages(array $formattedMessages): void
150151
$this->rotateFilesSync();
151152

152153
if (($fp = @fopen($this->logFile, 'a')) === false) {
154+
// Use error_log here to avoid recursion in logging system
153155
error_log("Unable to reopen log file after rotation: {$this->logFile}");
154156
return;
155157
}
@@ -207,6 +209,7 @@ public function shutdown(): void
207209
try {
208210
$this->worker->stop();
209211
} catch (\Throwable $e) {
212+
// Use error_log here to avoid recursion in logging system
210213
error_log('[CoroutineFileTarget] Error stopping worker: ' . $e->getMessage());
211214
}
212215
$this->worker = null;
@@ -220,6 +223,7 @@ public function __destruct()
220223
try {
221224
$this->shutdown();
222225
} catch (\Throwable $e) {
226+
// Use error_log here to avoid recursion in logging system
223227
error_log('[CoroutineFileTarget] Error during destruct: ' . $e->getMessage());
224228
}
225229
}

src/Log/LogWorker.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,12 @@ public function stop(): void
8181
$this->writeBufferedMessages();
8282

8383
if (!empty($this->messageBuffer)) {
84+
// Use error_log here to avoid recursion in logging system
8485
error_log('[LogWorker] Warning: ' . count($this->messageBuffer) . ' messages remain after stop');
8586
}
86-
87+
8788
if ($this->droppedMessages > 0) {
89+
// Use error_log here to avoid recursion in logging system
8890
error_log('[LogWorker] Warning: ' . $this->droppedMessages . ' messages were dropped (buffer full)');
8991
}
9092
}
@@ -134,6 +136,7 @@ private function writeMessages(array $messages): void
134136
$success = @file_put_contents($this->logFile, $text, FILE_APPEND | LOCK_EX);
135137

136138
if ($success === false) {
139+
// Use error_log here to avoid recursion in logging system
137140
error_log("LogWorker: Unable to write to log file: {$this->logFile}");
138141
return;
139142
}

src/Queue/CoroutineRedisQueue.php

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,6 @@ public function run($repeat, $timeout = 0)
154154
$duration = round(microtime(true) - $startTime, 2);
155155
$rate = $duration > 0 ? round($jobCount / $duration, 2) : 0;
156156
\Yii::info("Shutdown requested, stopping worker after current job. Processed {$jobCount} jobs in {$duration}s ({$rate} jobs/s)", __METHOD__);
157-
error_log("[Queue] Breaking from serial worker loop due to shutdown");
158157
break;
159158
}
160159
} catch (\yii\redis\SocketException $e) {
@@ -168,12 +167,9 @@ public function run($repeat, $timeout = 0)
168167
}
169168
}
170169
}
171-
172-
error_log("[Queue] Exited serial worker loop");
173170
} finally {
174171
// Return connection to pool when worker stops
175172
$this->redis->close();
176-
error_log("[Queue] Serial worker cleanup complete");
177173
}
178174
});
179175
}

src/Redis/CoroutineRedisConnection.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,7 @@ private static function registerShutdownHandler(): void
514514
try {
515515
self::shutdownAllPools();
516516
} catch (\Throwable $e) {
517-
// Silently handle errors during shutdown handler
517+
// Use error_log here to avoid dependency on Yii during shutdown
518518
error_log('[CoroutineRedisConnection] Error in shutdown handler: ' . $e->getMessage());
519519
}
520520
}

src/Server/RequestDispatcher.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,15 +95,15 @@ public function dispatch(Request $request, Response $response, SwooleCoroutineHt
9595
try {
9696
$store['db']->close();
9797
} catch (\Throwable $e) {
98-
error_log('[RequestDispatcher] Error closing DB: ' . $e->getMessage());
98+
Yii::error('Error closing DB: ' . $e->getMessage(), __CLASS__);
9999
}
100100
}
101101

102102
if (isset($store['redis']) && is_object($store['redis']) && method_exists($store['redis'], 'close')) {
103103
try {
104104
$store['redis']->close();
105105
} catch (\Throwable $e) {
106-
error_log('[RequestDispatcher] Error closing Redis: ' . $e->getMessage());
106+
Yii::error('Error closing Redis: ' . $e->getMessage(), __CLASS__);
107107
}
108108
}
109109
}

src/Server/ShutdownHelper.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ class ShutdownHelper
2929
* 2. Stops log workers (which flush their buffers to disk)
3030
* 3. Shuts down all log targets cleanly
3131
*
32-
* @param bool $verbose Whether to output progress messages to error_log
32+
* @param bool $verbose Whether to output progress messages (currently unused, errors always logged)
3333
*/
3434
public static function flushLogs(bool $verbose = true): void
3535
{
@@ -61,6 +61,7 @@ public static function flushLogs(bool $verbose = true): void
6161
}
6262
}
6363
} catch (\Throwable $e) {
64+
// Use error_log here to avoid recursion in logging system during shutdown
6465
error_log("Error stopping log worker '{$targetName}': {$e->getMessage()}");
6566
}
6667
}
@@ -71,31 +72,35 @@ public static function flushLogs(bool $verbose = true): void
7172
try {
7273
$target->shutdown();
7374
} catch (\Throwable $e) {
75+
// Use error_log here to avoid recursion in logging system during shutdown
7476
error_log("Error shutting down log target '{$targetName}': {$e->getMessage()}");
7577
}
7678
}
7779
}
7880
} catch (\Throwable $e) {
81+
// Use error_log here to avoid recursion in logging system during shutdown
7982
error_log('Error flushing logs: ' . $e->getMessage());
8083
}
8184
}
8285

8386
/**
8487
* Closes all database and Redis connection pools
8588
*
86-
* @param bool $verbose Whether to output progress messages to error_log
89+
* @param bool $verbose Whether to output progress messages (currently unused, errors always logged)
8790
*/
8891
public static function closeConnectionPools(bool $verbose = true): void
8992
{
9093
try {
9194
CoroutineDbConnection::shutdownAllPools();
9295
} catch (\Throwable $e) {
96+
// Use error_log during shutdown to ensure message is captured
9397
error_log('Error closing DB pools: ' . $e->getMessage());
9498
}
9599

96100
try {
97101
CoroutineRedisConnection::shutdownAllPools();
98102
} catch (\Throwable $e) {
103+
// Use error_log during shutdown to ensure message is captured
99104
error_log('Error closing Redis pools: ' . $e->getMessage());
100105
}
101106
}
@@ -106,7 +111,7 @@ public static function closeConnectionPools(bool $verbose = true): void
106111
* This executes both log flushing and connection pool closing
107112
* in the correct order.
108113
*
109-
* @param bool $verbose Whether to output progress messages to error_log
114+
* @param bool $verbose Whether to output progress messages (currently unused, errors always logged)
110115
*/
111116
public static function performGracefulShutdown(bool $verbose = true): void
112117
{

src/Server/SignalHandler.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class SignalHandler
3333
public function register(): void
3434
{
3535
if (!extension_loaded('pcntl')) {
36+
// Use error_log here since Yii may not be initialized yet
3637
error_log('[SignalHandler] PCNTL extension not loaded, signal handling disabled');
3738
return;
3839
}
@@ -99,11 +100,13 @@ private function handleShutdownSignal(int $signo): void
99100
$signalName = $signo === SIGTERM ? 'SIGTERM' : 'SIGINT';
100101

101102
if ($this->shutdownRequested) {
103+
// Use error_log during shutdown to ensure message is captured
102104
error_log("Forcing immediate exit");
103105
exit(1);
104106
}
105107

106108
$this->shutdownRequested = true;
109+
// Use error_log during shutdown to ensure message is captured
107110
error_log("Shutting down server...");
108111

109112
// Perform graceful shutdown in a coroutine
@@ -135,18 +138,21 @@ private function performGracefulShutdown(): void
135138
$elapsed = microtime(true) - $this->shutdownStartTime;
136139

137140
if ($elapsed >= self::SHUTDOWN_TIMEOUT) {
141+
// Use error_log during shutdown to ensure message is captured
138142
error_log("Shutdown timeout reached, skipping remaining callbacks");
139143
break;
140144
}
141145

142146
try {
143147
$config['callback']();
144148
} catch (\Throwable $e) {
149+
// Use error_log during shutdown to ensure message is captured
145150
error_log("Error in shutdown callback '{$name}': {$e->getMessage()}");
146151
}
147152
}
148153

149154
$totalTime = microtime(true) - $this->shutdownStartTime;
155+
// Use error_log during shutdown to ensure message is captured
150156
error_log(sprintf('Server shutdown completed in %.3f seconds', $totalTime));
151157

152158
// Wait briefly for remaining coroutines to complete
@@ -176,6 +182,7 @@ public function waitForInflightRequests(callable $checkCallback, float $maxWaitT
176182
Coroutine::sleep(self::CHECK_INTERVAL);
177183
}
178184

185+
// Use error_log during shutdown to ensure message is captured
179186
error_log('Request timeout, proceeding with shutdown');
180187
}
181188

@@ -203,6 +210,7 @@ private function waitForRemainingCoroutines(float $maxWaitTime): void
203210
$stats = Coroutine::stats();
204211
$remaining = (int)($stats['coroutine_num'] ?? 0);
205212
if ($remaining > 2) {
213+
// Use error_log during shutdown to ensure message is captured
206214
error_log("Warning: {$remaining} coroutines still active");
207215
}
208216
}

0 commit comments

Comments
 (0)