easyswoole用ioc重写系统日志类

easyswoole 3.3.7

定义自己的日志类

<?php

namespace App\Ioc;

use EasySwoole\Log\LoggerInterface;
use EasySwoole\Log\Logger;

class Log implements LoggerInterface
{

    private $logger;

    function __construct()
    {
        $this->logger = new Logger(EASYSWOOLE_LOG_DIR);
    }

    function log(?string $msg,int $logLevel = self::LOG_LEVEL_INFO,string $category = 'debug')
    {
        return $this->logger->log($msg, $logLevel, $category);
    }

    function console(?string $msg,int $logLevel = self::LOG_LEVEL_INFO,string $category = 'debug')
    {
        var_dump($msg);
        $this->logger->console($msg, $logLevel, $category);
    }
}

IOC覆盖系统日志类

项目根目录创建文件 bootstrap.php

<?php

use App\Ioc\Log;
use EasySwoole\Component\Di;
use EasySwoole\EasySwoole\SysConst;

Di::getInstance()->set(SysConst::LOGGER_HANDLER, Log::class);

分析

EasySwoole\EasySwoole\Core.php

查看源码中的registerErrorHandler方法

....
        //初始化配置Logger
        $logger = Di::getInstance()->get(SysConst::LOGGER_HANDLER);
        if(!$logger instanceof LoggerInterface){
            $logger = new DefaultLogger(EASYSWOOLE_LOG_DIR);
        }
        Logger::getInstance($logger);

        //初始化追追踪器
        $trigger = Di::getInstance()->get(SysConst::TRIGGER_HANDLER);
        if(!$trigger instanceof TriggerInterface){
            $trigger = new DefaultTrigger(Logger::getInstance());
        }
        Trigger::getInstance($trigger);

        //在没有配置自定义错误处理器的情况下,转化为trigger处理
        $errorHandler = Di::getInstance()->get(SysConst::ERROR_HANDLER);
        if(!is_callable($errorHandler)){
            $errorHandler = function($errorCode, $description, $file = null, $line = null){
                $l = new Location();
                $l->setFile($file);
                $l->setLine($line);
                Trigger::getInstance()->error($description,$errorCode,$l);
            };
        }
        set_error_handler($errorHandler);
....

查看 easyswoole-事件文档

查看 easyswoole-生命周期

发表评论