如何在扩展中注入 Joomla\CMS\Log\Log 并写入自定义通道?

解读

国内中大型企业在 Joomla 二开面试里,常把“日志怎么打”作为区分“只会套模板”与“懂底层”的分水岭。
核心考点有三:

  1. 是否知道 Joomla 4 之后日志容器化,必须走依赖注入而非 Log::add() 静态方法;
  2. 能否在扩展里声明自定义 logger,避免把业务日志与系统日志混在同一文件;
  3. 是否理解通道(channel)与类别的区别,以及如何在配置清单里注册,否则上线后运维无法按通道切分收集。
    一句话:企业要你“代码里见不到一行硬编码路径,却能在 Kibana 里一眼找到自家通道”。

知识点

  1. Joomla 4 依赖注入容器(Application 容器、LoggerAwareInterface)
  2. PSR-3 日志规范在 Joomla 中的落地:LoggerInterface、LogEntry
  3. channels 与 log categories 的差异:channel 决定写入哪个 handler,category 只是 entry 的一个字段
  4. 扩展清单文件 extension.xml 中 <logging> 节点用法,可声明通道、处理器与路径
  5. 运行时通过 $container->get(LoggerInterface::class)->withName('channel') 拿到指定通道
  6. 插件/模块/组件三者在注入时机上的差异:组件可在 Dispatcher 阶段,插件需在构造器里声明 LoggerAwareTrait

答案

以 Joomla 4 组件为例,分三步完成“注入 + 自定义通道 + 写日志”。

步骤 1:在 services/provider.php 里把 LoggerInterface 注入组件

use Joomla\CMS\Extension\ComponentInterface;
use Joomla\CMS\Log\LogServiceInterface;
use Joomla\Event\DispatcherInterface;

return new class implements ServiceProviderInterface {
    public function register(Container $container)
    {
        $container->set(
            ComponentInterface::class,
            function (Container $container) {
                $component = new \Acme\Component\Hello\Administrator\Extension\HelloComponent;
                // 关键:把容器里的 LoggerInterface 传进去
                $component->setLogger($container->get(LogServiceInterface::class)->createLogger('acme_hello'));
                return $component;
            }
        );
    }
};

步骤 2:在组件清单 hello.xml 中声明通道与文件

<logging>
    <channel name="acme_hello" level="info">
        <handler type="file" path="logs/acme_hello.log" format="{DATETIME} {LEVEL} {MESSAGE} {CONTEXT}" />
    </channel>
</logging>

安装时 Joomla 会自动把 acme_hello 通道注册到容器,运维后续可在 configuration.php 里覆盖路径,无需改代码。

步骤 3:在业务代码里使用

use Joomla\CMS\Log\LogServiceInterface;

class ItemModel extends BaseDatabaseModel
{
    private $logger;

    protected function populateState()
    {
        // 从容器拿通道
        $this->logger = $this->getContainer()->get(LogServiceInterface::class)
                         ->createLogger('acme_hello');
        $this->logger->info('开始同步商品', ['item_id' => 123]);
    }
}

至此,日志会独立写入 logs/acme_hello.log,通道名 acme_hello 也会作为 monolog 的 channel 字段,方便 ELK 按索引切分。

拓展思考

  1. 多实例 SaaS 场景下,同一通道如何按租户再分文件?
    可在 populateState() 里动态 withName('acme_hello_' . $tenantId),并在清单中把 handler 的 path 设为 logs/%channel%.log,Joomla 会自动替换 %channel% 占位符,实现“一个租户一个文件”,运维收集时加通配符即可。

  2. 上线后如何不改代码调整级别?
    在 configuration.php 追加

    public $log_levels = ['acme_hello' => 'error'];
    

    利用 Joomla 的 ConfigurationLoggerCreator,可实现运维侧热降级,开发无需发版。

  3. 安全审计要求日志不落本地,直接走 Kafka 怎么办?
    自定义一个 Monolog\Handler\KafkaHandler,在清单 <handler> 里写全类名,Joomla 4 的 LogService 支持自动实例化并注入构造函数依赖,实现“零改代码”切换中央日志。