【问题标题】:How to call for a monolog from the index.php?如何从 index.php 中调用独白?
【发布时间】:2019-09-22 20:30:46
【问题描述】:

有使用 PHP-DI 的 Monolog 示例(从手册中,有 2 个文件 - index.php 和 config.php:

<?php
// config.php

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

return [
    // ...

    Psr\Log\LoggerInterface::class => DI\factory(function () {
        $logger = new Logger('mylog');

        $fileHandler = new StreamHandler('path/to/your.log', Logger::DEBUG);
        $fileHandler->setFormatter(new LineFormatter());
        $logger->pushHandler($fileHandler);

        return $logger;
    }),
];

这个 config.php 在下面的代码中使用:

// index.php    
use DI\ContainerBuilder;

require __DIR__ . '/../vendor/autoload.php';

$containerBuilder = new ContainerBuilder;
$containerBuilder->addDefinitions(__DIR__ . '/config.php');
$container = $containerBuilder->build();

我现在如何在 index.php 中使用它?我经常这样使用 Monolog:

$log = new Logger('name'); 
$log->warning('Foo');

但是如何用Container调用它? 我能够在简单的 $container->set(), $container->get() 模式下做到这一点。但是以这种方式使用 Container Builder 我找不到办法。此外,当我制作var_dump($container) 时,其中没有任何记录器的迹象。

【问题讨论】:

    标签: php monolog php-di


    【解决方案1】:

    您需要将$log = new Logger('name') 替换为:

    $log = $container->get(\Psr\Log\LoggerInterface::class);
    

    查看这部分文档:http://php-di.org/doc/getting-started.html#3-create-the-objects

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 2012-05-15
      • 1970-01-01
      相关资源
      最近更新 更多