Strange behaviour when logging request/response


#1

For some reason I cannot fathom the json output from exception errorHandler is not logged to http.log in the code below. The json output for notFoundHandler however is logged as expected. Is this a known problem with Slim?

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'autoload.php';

$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;

$app = new \Slim\App(["settings" => $config]);

$c = $app->getContainer();
$c['logger'] = function($c) {
	$logger = new \Monolog\Logger('slim-app');
	$file_handler = new \Monolog\Handler\StreamHandler('http.log');
	$logger->pushHandler($file_handler);
	return $logger;
};

$app->add(function ($request, $response, $next) {
	$req = $request->getMethod() . ' ' . $request->getUri() . '" ' .
		$request->getBody();

	$response = $next($request, $response);
	
	$this->logger->debug($req . ' ' . $response->getBody());
	return $response;
});

$c['notFoundHandler'] = function ($c) {
	return function ($request, $response) use ($c) {
		$r['error']['type'] = 'page_not_found';
		$r['error']['message'] = 'Page not found';	
		return $c['response']->withJson($r, 404);
	};
};

$c['errorHandler'] = function ($c) {
	return function ($request, $response, $e) use ($c) {
		$r['error']['type'] = 'exception';
		$r['error']['message'] = $e->getMessage();
		return $c['response']->withJson($r, 500);
	};
};

$app->get('/test', function($req, $res) {
	throw new \Exception('test exception');
});

$app->run();
?>

#2

Is paid support available for Slim? I have not received any response to this. I need sample code that demonstrate how to log BOTH request and response including responses resulting from handling exceptions. I see no reason why above code should not work but it does not.


#3

There are people who develop with Slim that take on clients, check out https://twitter.com/slimphp as well as the #jobs channel in Slim’s Slack. There is no official support.

I don’t know the answer, but I suspect it has to do with the Exception being thrown before the middleware chain has reached $app and your logger is only firing after reaching $app. But that is a guess.