【问题标题】:How to set-up a generic leveraged logging using Monolog?如何使用 Monolog 设置通用的杠杆日志记录?
【发布时间】:2014-12-16 07:38:44
【问题描述】:

我正在编写一个带有 Symfony2 组件的控制台应用程序,我想为我的服务、命令等添加不同的日志记录通道。问题:创建一个新通道需要创建一个 Monolog 的新实例,我真的不知道如何以通用方式处理它,并且不需要传递流处理程序、通道和正确的代码来绑定所有服务中的一个和另一个。

我使用debug_backtrace()做到了这一点:

public function log($level, $message, array $context = array ())
{
    $trace = array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3), 1);
    $caller = $trace[0]['class'] !== __CLASS__ ? $trace[0]['class'] : $trace[1]['class'];
    if (!array_key_exists($caller, $this->loggers))
    {
        $monolog = new Monolog($caller);
        $monolog->pushHandler($this->stream);
        $this->loggers[$caller] = $monolog;
    }
    $this->loggers[$caller]->log($level, $message, $context);
}

无论我从哪里调用我的记录器,它都会为调用它的每个类创建一个通道。看起来很酷,但是一旦记录器被调用了很多时间,这就是在扼杀性能。

所以这是我的问题:

您是否知道一种更好的通用方法来为每个具有 logger 属性的类创建一个不同的独白通道?


以上代码打包测试:

composer.json

{
    "require" : {
        "monolog/monolog": "~1.11.0"
    }
}

test.php

<?php

require('vendor/autoload.php');

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

class Test
{

    public function __construct($logger)
    {
        $logger->info("test!");
    }

}

class Hello
{

    public function __construct($logger)
    {
        $logger->log(Monolog\Logger::ALERT, "hello!");
    }

}

class LeveragedLogger implements \Psr\Log\LoggerInterface
{

    protected $loggers;
    protected $stream;

    public function __construct($file, $logLevel)
    {
        $this->loggers = array ();
        $this->stream = new StreamHandler($file, $logLevel);
    }

    public function alert($message, array $context = array ())
    {
        $this->log(Logger::ALERT, $message, $context);
    }

    public function critical($message, array $context = array ())
    {
        $this->log(Logger::CRITICAL, $message, $context);
    }

    public function debug($message, array $context = array ())
    {
        $this->log(Logger::DEBUG, $message, $context);
    }

    public function emergency($message, array $context = array ())
    {
        $this->log(Logger::EMERGENCY, $message, $context);
    }

    public function error($message, array $context = array ())
    {
        $this->log(Logger::ERROR, $message, $context);
    }

    public function info($message, array $context = array ())
    {
        $this->log(Logger::INFO, $message, $context);
    }

    public function log($level, $message, array $context = array ())
    {
        $trace = array_slice(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3), 1);
        $caller = $trace[0]['class'] !== __CLASS__ ? $trace[0]['class'] : $trace[1]['class'];
        if (!array_key_exists($caller, $this->loggers))
        {
            $monolog = new Logger($caller);
            $monolog->pushHandler($this->stream);
            $this->loggers[$caller] = $monolog;
        }
        $this->loggers[$caller]->log($level, $message, $context);
    }

    public function notice($message, array $context = array ())
    {
        $this->log(Logger::NOTICE, $message, $context);
    }

    public function warning($message, array $context = array ())
    {
        $this->log(Logger::WARNING, $message, $context);
    }

}

$logger = new LeveragedLogger('php://stdout', Logger::DEBUG);

new Test($logger);
new Hello($logger);

用法

ninsuo:test3 alain$ php test.php
[2014-10-21 08:59:04] Test.INFO: test! [] []
[2014-10-21 08:59:04] Hello.ALERT: hello! [] []

【问题讨论】:

    标签: php logging monolog symfony-components


    【解决方案1】:

    对于在创建消费者之前决定应该使用哪个记录器,您会怎么想?这可以通过某种 DIC 或工厂轻松完成。

    <?php
    
    require('vendor/autoload.php');
    
    use Monolog\Logger;
    use Monolog\Handler\StreamHandler;
    use Psr\Log\LoggerInterface;
    use Monolog\Handler\HandlerInterface;
    
    class Test
    {
        public function __construct(LoggerInterface $logger)
        {
            $logger->info("test!");
        }
    }
    
    class Hello
    {
        public function __construct(LoggerInterface $logger)
        {
            $logger->log(Monolog\Logger::ALERT, "hello!");
        }
    }
    
    class LeveragedLoggerFactory
    {
        protected $loggers;
        protected $stream;
    
        public function __construct(HandlerInterface $streamHandler)
        {
            $this->loggers = array();
            $this->stream = $streamHandler;
        }
    
        public function factory($caller)
        {
            if (!array_key_exists($caller, $this->loggers)) {
                $logger = new Logger($caller);
                $logger->pushHandler($this->stream);
                $this->loggers[$caller] = $logger;
            }
    
            return $this->loggers[$caller];
        }
    }
    
    $loggerFactory = new LeveragedLoggerFactory(new StreamHandler('php://stdout', Logger::DEBUG));
    
    new Test($loggerFactory->factory(Test::class));
    new Hello($loggerFactory->factory(Hello::class));
    

    【讨论】:

    • 感谢您的想法。我也会发布一个答案(我选择覆盖服务容器,它会自动向 LoggerAware 服务注入一个记录器),但无论如何我都会奖励你。
    【解决方案2】:

    我终于创建了一个扩展标准 Symfony2 容器的 MonologContainer 类,并将 Logger 注入到 LoggerAware 服务。重载服务容器的get()方法,可以得到服务的ID,作为logger的通道。

    <?php
    
    namespace Fuz\Framework\Core;
    
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\DependencyInjection\ContainerInterface;
    use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
    use Monolog\Handler\HandlerInterface;
    use Monolog\Logger;
    use Psr\Log\LoggerAwareInterface;
    
    class MonologContainer extends ContainerBuilder
    {
    
        protected $loggers = array ();
        protected $handlers = array ();
        protected $processors = array ();
    
        public function __construct(ParameterBagInterface $parameterBag = null)
        {
            parent::__construct($parameterBag);
        }
    
        public function pushHandler(HandlerInterface $handler)
        {
            foreach (array_keys($this->loggers) as $key)
            {
                $this->loggers[$key]->pushHandler($handler);
            }
            array_unshift($this->handlers, $handler);
            return $this;
        }
    
        public function popHandler()
        {
            if (count($this->handlers) > 0)
            {
                foreach (array_keys($this->loggers) as $key)
                {
                    $this->loggers[$key]->popHandler();
                }
                array_shift($this->handlers);
            }
            return $this;
        }
    
        public function pushProcessor($callback)
        {
            foreach (array_keys($this->loggers) as $key)
            {
                $this->loggers[$key]->pushProcessor($callback);
            }
            array_unshift($this->processors, $callback);
            return $this;
        }
    
        public function popProcessor()
        {
            if (count($this->processors) > 0)
            {
                foreach (array_keys($this->loggers) as $key)
                {
                    $this->loggers[$key]->popProcessor();
                }
                array_shift($this->processors);
            }
            return $this;
        }
    
        public function getHandlers()
        {
            return $this->handlers;
        }
    
        public function get($id, $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE)
        {
            $service = parent::get($id, $invalidBehavior);
            return $this->setLogger($id, $service);
        }
    
        public function setLogger($id, $service)
        {
            if ($service instanceof LoggerAwareInterface)
            {
                if (!array_key_exists($id, $this->loggers))
                {
                    $this->loggers[$id] = new Logger($id, $this->handlers, $this->processors);
                }
                $service->setLogger($this->loggers[$id]);
            }
            return $service;
        }
    
    }
    

    使用示例:

    test.php

    #!/usr/bin/env php
    <?php
    
    use Symfony\Component\Config\FileLocator;
    use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
    use Monolog\Logger;
    use Monolog\Handler\StreamHandler;
    use Fuz\Framework\Core\MonologContainer;
    
    if (!include __DIR__ . '/vendor/autoload.php')
    {
        die('You must set up the project dependencies.');
    }
    
    $container = new MonologContainer();
    
    $loader = new YamlFileLoader($container, new FileLocator(__DIR__));
    $loader->load('services.yml');
    
    $handler = new StreamHandler(__DIR__ ."/test.log", Logger::WARNING);
    $container->pushHandler($handler);
    
    $container->get('my.service')->hello();
    

    services.yml

    parameters:
        my.service.class: Fuz\Runner\MyService
    
    services:
    
        my.service:
            class: %my.service.class%
    

    MyService.php

    <?php
    
    namespace Fuz\Runner;
    
    use Psr\Log\LoggerAwareInterface;
    use Psr\Log\LoggerInterface;
    
    class MyService implements LoggerAwareInterface
    {
    
        protected $logger;
    
        public function setLogger(LoggerInterface $logger)
        {
            $this->logger = $logger;
        }
    
        public function hello()
        {
            $this->logger->alert("Hello, world!");
        }
    
    }
    

    演示

    ninsuo:runner alain$ php test.php
    ninsuo:runner alain$ cat test.log
    [2014-11-06 08:18:55] my.service.ALERT: Hello, world! [] []
    

    【讨论】:

      【解决方案3】:

      你可以试试这个

      <?php
      
      use Monolog\Logger;
      use Monolog\Handler\StreamHandler;
      use Monolog\Handler\FirePHPHandler;
      
      
      class Loggr{
      
          private static $_logger;
          public $_instance;
          public $_channel;
      
          private function __construct(){
              if(!isset(self::$_logger))
                  self::$_logger = new Logger('Application Log');
          }
      
          // Create the logger
          public function logError($error){
                  self::$_logger->pushHandler(new StreamHandler(LOG_PATH . 'application.'. $this->_channel . '.log', Logger::ERROR));
                  self::$_logger->addError($error);
          }
      
          public function logInfo($info){
                  self::$_logger->pushHandler(new StreamHandler(LOG_PATH . 'application.'. $this->_channel . '.log', Logger::INFO));
                  self::$_logger->addInfo($info);
          }
      
          public static function getInstance($channel) {
      
              $_instance = new Loggr();
              $_instance->_channel = strtolower($channel);        
      
              return $_instance;
          }
      }
      

      可以作为

      class LeadReport extends Controller{
      
          public function __construct(){
      
              $this->logger = Loggr::getInstance('cron');
              $this->logger->logError('Error generating leads');
      
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-07-24
        • 2013-01-14
        • 2015-06-09
        • 1970-01-01
        • 2017-03-01
        • 2014-07-03
        • 2023-03-11
        • 2020-02-21
        • 1970-01-01
        相关资源
        最近更新 更多