简体   繁体   English

如何从index.php中调用monolog?

[英]How to call for a monolog from the index.php?

There is example of using Monolog with PHP-DI (from manual, there are 2 files - index.php and config.php: 有一个使用Monolog和PHP-DI的例子(来自手册,有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;
    }),
];

This config.php is using in the below code: 这个config.php在下面的代码中使用:

// index.php    
use DI\ContainerBuilder;

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

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

How could I use it now in index.php? 我怎么能在index.php中使用它? Regularly I use Monolog this way: 我经常以这种方式使用Monolog:

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

But how to call it with Container ? 但是如何用Container调用呢 I was able to do it in simple $container->set(), $container->get() mode. 我能够在简单的$ container-> set(),$ container-> get()模式下完成。 But in this way using Container Builder I can't find a way to do it. 但是这样使用Container Builder我找不到办法。 Moreover when I make var_dump($container) there are no any logger's signs in it. 此外,当我创建var_dump($container) ,没有任何记录器的标志。

You need to replace $log = new Logger('name') with: 您需要将$log = new Logger('name')替换为:

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

See this part of the documentation: http://php-di.org/doc/getting-started.html#3-create-the-objects 请参阅文档的这一部分: http//php-di.org/doc/getting-started.html#3-create-the-objects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM