添加发送到日志的用户详细信息和发布参数

日志非常重要。由于缺乏有关错误发生方式和时间的信息,重新创建错误上下文有时会非常痛苦。

此示例显示:

  • 如何在错误日志中添加用户数据

  • 如何添加发生错误时发送的 post 参数

  • 如何使用 WebProcessor 添加有关请求的所有数据,如:

    • 网址
    • IP
    • http 方法
    • 服务器
    • 引用

服务配置

services:          
    # Permits to convert logs in HTML format for email notification
    monolog.formatter.html:
        class: Monolog\Formatter\HtmlFormatter

    # Add request data (url, ip, http method, server, referrer)
    monolog.processor.web_processor:
        class: Monolog\Processor\WebProcessor
        tags:
            - { name: monolog.processor, method: __invoke } 

    # Custom class to include user's data and posted parameters in the logs
    monolog.processor.user:
        class: Company\ToolBoxBundle\Services\Monolog\ExtraProcessor
        arguments:  ["@security.token_storage"]
        tags:
            - { name: monolog.processor }
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }    

服务代码

namespace Company\ToolBoxBundle\Services\Monolog;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class ExtraProcessor
{
    /**
    * @var string
    */
    private $postParams = null;    

    /**
    * @var TokenStorageInterface
    */
    private $tokenStorage = null;

    /**
    * @var \Company\UserBundle\Entity\User
    */
    private $user = null;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }
        
    // Called when an error occurred and a log (record) is creating
    public function __invoke(array $record)
    {
        if (null !== $this->user) {
            // $this->user is your user's entity. Extract all pertinent data you would need. In this case, getUserDetails method create a summary including alias, name, role, ...
            $record['extra']['user'] = $this->user->getUserDetails();
        }

        if (null !== $this->postParams) {
            // Includes all posted parameter when the error occurred
            $record['extra']['postParams'] = $this->postParams;
        }

        return $record;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        // Retain post parameters sent (serialized) in order to log them if needed
        $postParams = $event->getRequest()->request->all();
        if(false === empty($postParams)){
            $this->postParams = serialize($postParams);
        }  

        // Do not continue if user is not logged
        if (null === $token = $this->tokenStorage->getToken()) {
            return;
        }

        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return;
        }

        // Retain the user entity in order to use it
        $this->user = $user;
    }
}