在配置Rollbar Monolog配置时,可以设置的一个选项是person_fn
功能。该配置Rollbar期望是某种“可调用”,调用时将返回有关用户的信息。
为了获取有关当前用户的信息,该方法将需要Session处理程序来获取当前登录的用户。我可以写一个这样做的服务:
<?php
class UserService {
private $session;
public function __construct(SessionInterface $session) {
$this->session = $session;
}
public function RollbarUserFn() {
$u = $this->session->get('current_user');
return array(
'id' => $u['id'],
'username' => $u['username']
);
}
}
现在,如果只使用call_user_func
,RollbarUserFn
方法不是静态的(因为它有依赖关系),所以不能使用"UserService::RollbarUserFn"
(一个字符串),而是实例化它和传递对象:
$us = new UserService($sessionInterface);
call_user_func(array($us, 'RollbarUserFn'));
但是如何在配置YAML文件中执行相同的操作?我尝试过类似的东西:
monolog:
handlers:
rollbar:
type: rollbar
token: '123123123'
config:
environment: '%env(APP_ENV)%'
person_fn: [ '@UserService', 'RollbarUserFn' ]
但是这会引发错误,person_fn
配置节点应该是标量,而不是数组
答案 0 :(得分:0)
您可以像这样从RollbarHandlerFactory
装饰rollbar/rollbar-php-symfony-bundle
:
#config/services_prod.yaml
services:
App\Service\RollbarHandlerFactory:
decorates: Rollbar\Symfony\RollbarBundle\Factories\RollbarHandlerFactory
arguments:
- '@service_container'
- ['password', 'plainPassword', 'proxyInitialized', 'proxyInitializer', 'photo']
并重新配置记录器
<?php
namespace App\Service;
use Rollbar\Rollbar;
use Rollbar\Symfony\RollbarBundle\Factories\RollbarHandlerFactory as BaseFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
class RollbarHandlerFactory extends BaseFactory
{
public function __construct(ContainerInterface $container, array $scrubFields = [])
{
parent::__construct($container);
Rollbar::logger()->configure([
'person_fn' => function () use ($container, $scrubFields) {
try {
$token = $container->get('security.token_storage')->getToken();
if ($token) {
/** @var \App\Model\User $user */
$user = $token->getUser();
$serializer = $container->get('serializer');
$person = \json_decode($serializer->serialize($user, 'json'), true);
foreach ($scrubFields as $field) {
unset($person[$field]);
}
$person['id'] = $user->getEmail();
return $person;
}
} catch (\Exception $exception) {
// Ignore
}
}
]);
}
}