1

我正在使用 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);

Usage

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

3 回答 3

2

在创建消费者之前决定应该使用哪个记录器,您会怎么想?这可以通过某种 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));
于 2014-10-28T12:29:33.337 回答
0

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

<?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!");
    }

}

Demo

ninsuo:runner alain$ php test.php
ninsuo:runner alain$ cat test.log
[2014-11-06 08:18:55] my.service.ALERT: Hello, world! [] []
于 2014-11-06T07:25:16.140 回答
0

你可以试试这个

<?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');

    }
}
于 2015-02-25T07:29:44.827 回答