Using custom logger service in AuthenticationHandler class in Symfony2
Question
In brief I am trying to use a logger service that I defined inside a custom handler service.
My 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 ]
The "services:" is well indented in my code, dnt worry.
My 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;
}
}
I am getting:
Fatal error: Call to a member function addWarning() on a non-object in ... Panasonic\LoginBundle\Handler\AuthenticationHandler.php on line 22
Note: I am aware I should return a response in onAuthenticationSuccess, it's in fact uncomplete, but I know it works, I got results from the var_dumps.
I guess the injection is not ok, how should it be done? I can't figure out what to do here. Please help
the references I checked: Access services inside a regular class
Solution
Check your contructor name... I guess it is not called...
public function __construct()
{
// ...
}
I've written an article exactly explaining how to achieve that : http://blog.alterphp.com/2012/04/set-up-specific-log-file-for.html