From 5bf08210aa8c8001530dd462f277aa594b0dfc51 Mon Sep 17 00:00:00 2001 From: Thibaud Fabre Date: Tue, 29 Sep 2015 18:16:12 +0200 Subject: [PATCH] Enable application logging from API calls --- lib/Alchemy/Phrasea/Application/Api.php | 5 ++++- .../ApiExceptionHandlerSubscriber.php | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/lib/Alchemy/Phrasea/Application/Api.php b/lib/Alchemy/Phrasea/Application/Api.php index 55aa2e4a06..57b0f02ec2 100644 --- a/lib/Alchemy/Phrasea/Application/Api.php +++ b/lib/Alchemy/Phrasea/Application/Api.php @@ -41,7 +41,10 @@ return call_user_func(function ($environment = PhraseaApplication::ENV_PROD) { $app->loadPlugins(); $app['exception_handler'] = $app->share(function ($app) { - return new ApiExceptionHandlerSubscriber($app); + $handler = new ApiExceptionHandlerSubscriber($app); + $handler->setLogger($app['monolog']); + + return $handler; }); $app['monolog'] = $app->share($app->extend('monolog', function (Logger $monolog) { $monolog->pushProcessor(new WebProcessor()); diff --git a/lib/Alchemy/Phrasea/Core/Event/Subscriber/ApiExceptionHandlerSubscriber.php b/lib/Alchemy/Phrasea/Core/Event/Subscriber/ApiExceptionHandlerSubscriber.php index d4b6b98ad1..839cfc60d1 100644 --- a/lib/Alchemy/Phrasea/Core/Event/Subscriber/ApiExceptionHandlerSubscriber.php +++ b/lib/Alchemy/Phrasea/Core/Event/Subscriber/ApiExceptionHandlerSubscriber.php @@ -13,6 +13,8 @@ namespace Alchemy\Phrasea\Core\Event\Subscriber; use Alchemy\Phrasea\Application; use Alchemy\Phrasea\Controller\Api\Result; +use Psr\Log\LoggerInterface; +use Psr\Log\NullLogger; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; @@ -27,9 +29,17 @@ class ApiExceptionHandlerSubscriber implements EventSubscriberInterface { private $app; + private $logger; + public function __construct(Application $app) { $this->app = $app; + $this->logger = new NullLogger(); + } + + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; } public static function getSubscribedEvents() @@ -64,6 +74,13 @@ class ApiExceptionHandlerSubscriber implements EventSubscriberInterface $code = 500; } + if ($code == 500) { + $this->logger->error($e->getMessage(), [ + 'code' => $e->getCode(), + 'trace' => $e->getTrace() + ]); + } + if ($e instanceof HttpExceptionInterface) { $headers = $e->getHeaders(); }