Skip to content

Instantly share code, notes, and snippets.

@DayS
Created March 4, 2020 17:31
Show Gist options
  • Save DayS/d92865f370e4bb9c4e742a9fc0d5e80a to your computer and use it in GitHub Desktop.
Save DayS/d92865f370e4bb9c4e742a9fc0d5e80a to your computer and use it in GitHub Desktop.
Bugsnag session tracking for Symfony projects to allow stability score computing
bugsnag:
api_key: "%env(BUGSNAG_API_KEY)%"
app_version: "%env(PROJECT_VERSION)%"
services:
App\Core\Bugsnag\SessionBugsnagListener:
arguments:
- '@service_container'
tags:
- { name: "kernel.event_subscriber" }
<?php
namespace App\Core\Bugsnag;
use Bugsnag\Client;
use InvalidArgumentException;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class SessionBugsnagListener implements EventSubscriberInterface
{
/** @var Client */
private $client;
/** @var ContainerInterface */
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
$this->client = $this->container->get('bugsnag');
}
public function onKernelRequest($event)
{
// Compatibility with Symfony < 5 and Symfony >=5
if (!$event instanceof GetResponseEvent && !$event instanceof RequestEvent) {
throw new InvalidArgumentException('onKernelRequest function only accepts GetResponseEvent and RequestEvent arguments');
}
if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) {
return;
}
$this->client->startSession();
}
public function onKernelResponse(ResponseEvent $event)
{
// $this->client->getSessionTracker()->sendSessions();
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => ['onKernelRequest', 256],
KernelEvents::RESPONSE => ['onKernelResponse', 256]
];
}
}
@DayS
Copy link
Author

DayS commented Mar 4, 2020

As stated on Bugsnag's doc, a session for a server-side project is equivalent to : "a request is processed". This snippet achieve this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment