0

在配置 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']
    ); 
  }
}

现在,如果只是 using 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配置节点应为标量,而不是数组

4

1 回答 1

0

你可以这样装饰RollbarHandlerFactoryrollbar/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
                }
            }
        ]);
    }
}

于 2019-06-05T16:29:34.690 回答