【问题标题】:Using custom logger service in AuthenticationHandler class in Symfony2在 Symfony2 的 AuthenticationHandler 类中使用自定义记录器服务
【发布时间】:2012-04-16 15:04:57
【问题描述】:

简而言之,我正在尝试使用我在自定义处理程序服务中定义的记录器服务。

我的 config.yml

services:
authentication_handler:
    class: Panasonic\LoginBundle\Handler\AuthenticationHandler
    arguments: [ @custom_logger ]

custom_logger:
    class: Monolog\Logger
    arguments: [login]
    calls:
        - [ pushHandler, [ @custom_logger_stream ]]

custom_logger_stream:
    class: Monolog\Handler\RotatingFileHandler
    arguments: [ %kernel.logs_dir%/test.log, 30, 200 ]

“服务:”在我的代码中缩进很好,不用担心。

我的 Bundle/Handler/AuthenticationHandler

namespace Panasonic\LoginBundle\Handler;

use Monolog\Logger;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthenticationHandler implements AuthenticationSuccessHandlerInterface
{

private $custom_logger;

public function __constructor(Logger $custom_logger)
{
    $this->custom_logger = $custom_logger;
}

public function onAuthenticationSuccess(Request $request,
                                        TokenInterface $token)
{
    $log = $this->custom_logger;

    $log->addWarning('Foo');
    $log->addError('Bar');
    die;

    //        var_dump($token); die;
    //        var_dump($request->getSession()); die;
}
}

我得到:

Fatal error: Call to a member function addWarning() on a non-object in ... Panasonic\LoginBundle\Handler\AuthenticationHandler.php on line 22

注意:我知道我应该在 onAuthenticationSuccess 中返回一个响应,它实际上是不完整的,但我知道它有效,我从 var_dumps 中得到了结果。

我猜是注射不行,应该怎么做?我不知道在这里做什么。请帮忙

我检查的参考资料: Access services inside a regular class

http://martinsikora.com/symfony2-and-dependency-injection

【问题讨论】:

  • 我认为错误出现在 custom_logger: class: Monolog\LoggerSymfony\Bridge\Monolog\Logger 中,应该在我的处理程序中使用 LoggerInterface。我通过重新调整我的代码解决了 PéCé 提供的链接的问题。

标签: symfony config monolog


【解决方案1】:

检查您的构造函数名称...我猜它没有被调用...

public function __construct()
{
    // ...
}

我已经写了一篇文章准确地解释了如何实现这一点:http://blog.alterphp.com/2012/04/set-up-specific-log-file-for.html

【讨论】:

  • 谢谢,您的博文帮助我找到了错误。干净代码的好例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 2012-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多