我有以下课程:
namespace AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
class UserRegistrationListener implements EventSubscriberInterface
{
protected $logger;
public function __construct($logger)
{
$this->logger = $logger;
}
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInit',
);
}
/**
* take action when registration is initialized
* set the username to a unique id
* @param \FOS\UserBundle\Event\FormEvent $event
*/
public function onRegistrationInit(UserEvent $userevent)
{
$this->logger->info("Log Something");
$user = $userevent->getUser();
$user->setUsername(uniqid());
}
}
Run Code Online (Sandbox Code Playgroud)
而且我一直在努力用几个小时的时间记录一下monolog的东西,但没有运气.
我已经阅读了很多文档,我相信我需要以某种方式'注入'monolog作为服务.然而,我所读到的内容似乎并不清楚.
一些细节:
#config_dev.yml
monolog:
channels: [chris]
handlers:
mylog:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%_chris.log"
channels: chris
formatter: monolog.my_line_formatter
Run Code Online (Sandbox Code Playgroud)
.
#services.yml
services:
monolog.my_line_formatter:
class: Monolog\Formatter\LineFormatter
arguments: [~, ~, true]
app.user_registration:
class: AppBundle\EventListener\UserRegistrationListener
arguments: [@logger] ## changed to [@monolog.logger.chris] to us custom channel
tags:
- { name: kernel.event_subscriber }
Run Code Online (Sandbox Code Playgroud)
我需要做些什么才能让Monolog在我的课程中使用我的格式化程序?
更新: @griotteau我已经完成了你在答案中发布的内容,但我仍然收到错误消息:
CRITICAL - 未捕获的PHP异常Symfony\Component\Debug\Exception\ContextErrorException:"警告:缺少参数1的AppBundle\EventListener\UserRegistrationListener :: __ construct(),在... filepath ...\app\cache\dev\appDevDebugProjectContainer中调用.php在第384行并定义为"at ... filepath ...\src\AppBundle\EventListener\UserRegistrationListener.php第18行
已解决的错误我已经有了同一个班级的服务(未在ym问题中显示).@griotteau的回答是正确的.
您可以在声明服务时传递参数
在services.yml中:
app.user_registration:
class: AppBundle\EventListener\UserRegistrationListener
arguments: [@logger]
tags:
- { name: kernel.event_subscriber }
Run Code Online (Sandbox Code Playgroud)
在您的类中,添加一个构造函数:
protected $logger;
public function __construct($logger)
{
$this->logger = $logger;
}
Run Code Online (Sandbox Code Playgroud)
所以当你想添加一个日志时:
$this->logger->info(...);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1144 次 |
| 最近记录: |