Sök…
Lägg till användarinformation och postade parametrar skickade till loggar
Loggar är mycket viktiga. Återskapa en felkontext kan ibland vara mycket smärtsam på grund av bristen på information om hur och när felet inträffade.
Detta exempel visar:
Hur man lägger till användardata i felloggarna
Hur man lägger till inläggsparametrar som skickades när ett fel inträffade
Hur man använder WebProcessor för att lägga till all information om begäran som:
- url
- ip
- http-metod
- server
- hänvisnings
Servicekonfiguration
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 }
Servicekod
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;
}
}
Modified text is an extract of the original Stack Overflow Documentation
Licensierat under CC BY-SA 3.0
Inte anslutet till Stack Overflow