我正在尝试创建一个自定义monolog处理器,以将当前用户附加到错误邮件程序。
宣布这样的服务时:
monolog.processor.mail:
class: MyVendor\Monolog\Processor\MailProcessor
arguments:
- @mailer
- @security.context
tags:
- { name: monolog.processor, method: processRecord }
我得到一个循环引用:
[Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException]
Circular reference detected for service "monolog.processor.mail",
path: "router -> monolog.logger.router -> monolog.processor.mail
-> security.context -> security.authentication.manager
-> fos_user.user_provider.username_email-> fos_user.user_manager
-> doctrine.orm.default_entity_manager -> doctrine.dbal.default_connection
-> doctrine.dbal.logger -> monolog.logger.doctrine".
这里的最佳实践解决方案是什么?
相关论坛帖子: http://forum.symfony-project.org/viewtopic.php?t=40306&p=131081#p131143
此主题显示:
还尝试使用此脚本http://pastebin.com/AuvFgTY3从会话中获取用户。
if ($this->session !== null) {
if ($this->session->has($this->securityKey)) {
$token = unserialize($this->session->get($this->securityKey));
$this->currentUser = $token->getUser();
}
}
这给出了以下错误:
Warning: ini_set(): A session is active. You cannot change the session module's ini settings at this time in
C:\inetpub\symfony23\vendor\symfony\symfony\src\Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler.php
on line 56
我确实知道还没有为很早就请求记录器的服务构建security.context。对于我的课程,这不是问题,因为我将用户设置为undefined
。因此,理想情况下,security.context
将在创建security.context
服务之后进行注册。但是我无法改变记录器的优先级,因为它很早就需要构建。
所以也许这个问题可以解决:如何在security.context初始化之后再次重新创建服务?不确定范围原型是否会对此有所帮助?
答案 0 :(得分:4)
在内核请求上创建处理程序并提取用户:
// src/AppBundle/Monolog/UserProcessor.php
namespace AppBundle\Monolog;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class UserProcessor
{
private $tokenStorage;
private $user;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function __invoke(array $record)
{
if (null !== $this->user) {
$record['extra']['user'] = $this->user->getUsername();
}
return $record;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (null === $token = $this->tokenStorage->getToken()) {
return;
}
if (!is_object($user = $token->getUser())) {
// e.g. anonymous authentication
return;
}
$this->user = $user;
}
}
注册新处理器:
# app/config/services.yml
services:
monolog.processor.user:
class: AppBundle\Monolog\UserProcessor
arguments: ["@security.token_storage"]
tags:
- { name: monolog.processor }
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
Symfony文档存在问题