Added logger to classes that catch errors in order to log them

This commit is contained in:
Alejandro Celaya
2016-08-08 12:33:58 +02:00
parent fff058f44b
commit 34753ca7d3
8 changed files with 85 additions and 19 deletions

View File

@@ -4,6 +4,8 @@ namespace Shlinkio\Shlink\Core\Action;
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Shlinkio\Shlink\Core\Service\UrlShortener;
use Shlinkio\Shlink\Core\Service\UrlShortenerInterface;
use Shlinkio\Shlink\Core\Service\VisitsTracker;
@@ -21,18 +23,27 @@ class RedirectAction implements MiddlewareInterface
* @var VisitsTrackerInterface
*/
private $visitTracker;
/**
* @var null|LoggerInterface
*/
private $logger;
/**
* RedirectMiddleware constructor.
* @param UrlShortenerInterface $urlShortener
* @param VisitsTrackerInterface $visitTracker
* @param LoggerInterface|null $logger
*
* @Inject({UrlShortener::class, VisitsTracker::class})
* @Inject({UrlShortener::class, VisitsTracker::class, "Logger_Shlink"})
*/
public function __construct(UrlShortenerInterface $urlShortener, VisitsTrackerInterface $visitTracker)
{
public function __construct(
UrlShortenerInterface $urlShortener,
VisitsTrackerInterface $visitTracker,
LoggerInterface $logger = null
) {
$this->urlShortener = $urlShortener;
$this->visitTracker = $visitTracker;
$this->logger = $logger ?: new NullLogger();
}
/**
@@ -81,6 +92,7 @@ class RedirectAction implements MiddlewareInterface
return new RedirectResponse($longUrl);
} catch (\Exception $e) {
// In case of error, dispatch 404 error
$this->logger->error('Error redirecting to long URL.' . PHP_EOL . $e);
return $this->notFoundResponse($request, $response, $out);
}
}

View File

@@ -99,7 +99,7 @@ class UrlShortener implements UrlShortenerInterface
$this->em->close();
}
throw new RuntimeException('An error occured while persisting the short URL', -1, $e);
throw new RuntimeException('An error occurred while persisting the short URL', -1, $e);
}
}