作者 zed

优化日志写入

... ... @@ -9,6 +9,7 @@ class StreamLogger
protected int $flushSize = 50; // 缓冲条数
protected int $flushInterval = 1000; // 最长缓存时间(毫秒)
protected array $lastWrite = []; // 每个 channel 上次写盘时间戳(毫秒)
protected bool $timerCreated = false; // 是否已创建定时器
public function __construct(string $basePath = null)
{
... ... @@ -23,13 +24,34 @@ class StreamLogger
if (!is_dir($this->basePath)) {
mkdir($this->basePath, 0777, true);
}
// 自动延迟启动(防止主程序部分服务未完成初始化。)
$this->bootTickSafely();
}
protected function bootTickSafely()
{
// 如果已经创建,避免重复
if (!empty($this->timerCreated)) {
return;
}
$this->timerCreated = true;
// 启动定时器(仅 Swoole 环境有效)
if (class_exists(\Swoole\Timer::class)) {
\Swoole\Timer::tick(1000, function () {
$this->flushByInterval();
});
// 如果已经在协程环境 → 直接创建 tick
if (\Swoole\Coroutine::getCid() > 0) {
$this->startTick();
return;
}
// 不在协程 → 用 defer 延迟到协程环境创建后
\Swoole\Coroutine::defer(function () {
$this->startTick();
});
}
protected function startTick()
{
\Swoole\Timer::tick(1000, function () {
$this->flushByInterval();
});
}
public function log($channel, $content): void
... ...