Skip to content

Instantly share code, notes, and snippets.

@Veve2
Created January 9, 2017 13:30
Show Gist options
  • Save Veve2/00a83af7ce8cfa6080c50cc7c8c6ed38 to your computer and use it in GitHub Desktop.
Save Veve2/00a83af7ce8cfa6080c50cc7c8c6ed38 to your computer and use it in GitHub Desktop.
Including extra debugging Information in Symfony error log
# app/config/config.yml
services:
monolog.formatter.request:
class: Monolog\Formatter\LineFormatter
arguments:
- "[%%datetime%%] [%%extra.username%%] %%channel%%.%%level_name%%: %%message%% %%context%% [%%extra.postParams%%]\n"
# app/config/config_prod.yml
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
nested:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
formatter: monolog.formatter.request
console:
type: console
<?php
namespace AppBundle\Monolog;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @DI\Service("app.monolog.extra_processor")
* @DI\Tag("monolog.processor")
*/
class ExtraProcessor
{
/**
* @DI\Inject("security.token_storage")
*
* @var TokenStorageInterface
*/
public $tokenStorage;
/**
* @var UserInterface
*/
private $user;
/**
* @var array
*/
private $postParams;
/**
* @param array $record
*
* @return array
*/
public function __invoke(array $record)
{
if ($this->user instanceof UserInterface) {
$record['extra']['user'] = [
'username' => $this->user->getUsername(),
];
}
if (null !== $this->postParams) {
$record['extra']['postParams'] = $this->postParams;
}
return $record;
}
/**
* @DI\Observe("kernel.request")
*
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$postParams = $event->getRequest()->request->all();
if (false === empty($postParams)) {
$this->postParams = serialize($postParams);
}
$token = $this->tokenStorage->getToken();
if (null === $token) {
return;
}
$user = $token->getUser();
if (!($user instanceof UserInterface)) {
return;
}
$this->user = $user;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment