Logging request details

I like to logging request and response in my project.

I can able to log the response details.

But I need to log the details of the request.

How to do that?

I am using the following code.

<?php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

use Monolog\Formatter\LineFormatter;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Interop\Container\ContainerInterface;
require 'vendor/autoload.php';

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

$config['db']['host']   = "localhost";
$config['db']['user']   = "user";
$config['db']['pass']   = "user";
$config['db']['dbname'] = "slim";

$app = new \Slim\App(["settings" => $config]);
$app->get('/', function (Request $req,  Response $res, $args = []) {

$dateFormat = "y-m-d H:i:s";
$output = "[%datetime%]  %level_name% : %message%\n";

$formatter = new LineFormatter($output, $dateFormat);

$stream = new StreamHandler("logfiles/".date('m-d')."_file.log", Logger::INFO);
$stream->setFormatter($formatter);

	$log = new Logger('Request');
	$log->pushHandler($stream);
	$action = $req->getQueryParams()['action'];		//checks _GET [IS PSR-7 compliant]

	foreach($req->getQueryParams() as $params)
	{
		$log->info($params);
	}

	switch($action)
	{
		case "ListEvents":
			$userid = $req->getQueryParams()['userid'];
			$details = array('key'=>'Test', 'value'=>'Success', 'userid'=>$userid);
			$res = $res->withJSON($details);
			$log->info($res);
			return $res;
			break;
	}
});

// Run app
$app->run();
?>

I am getting following result in log

17-02-14 16:13:08] INFO : ListEvents
[17-02-14 16:13:08] INFO : 90
[17-02-14 16:13:08] INFO : HTTP/1.1 200 OK Content-Type: application/json;charset=utf-8 {“key”:“Test”,“value”:“Success”,“userid”:“90”}

But I need request log as

Request: “action=ListEvents&userid=90”
Response: {“action”:“ListEvents”, “key”:“Test”, “value”:“Success”, “userid”:“90”}

How to do that? Any ideas?

You can try:

$log->info('Request: "' . http_build_query($req->getQueryParams()) . '"');
$log->info('Response: ' . json_encode(['action' => 'ListEvents', 'key' => 'Test', 'value' => 'Success', 'userid' => $userid]));

Hi!

Very useful information here. I would like to log RESPONSES from different types of request without including detailed information about parameters. Will be great to get the full response values.

Now I use a middleware which log the request information:

<?php namespace App\Middleware; class MonologMiddleware extends Middleware { public function __invoke ($request, $response, $next) { $this->container->logger->debug("Logger, debug mode: ..."); $response = $next($request, $response); return $response; } } == Is it possible? Thank you.

I haven’t tried, but it looks possible. To get the response, add the logging after the call to $next, e.g.:

class MonologMiddleware extends Middleware
{
    public function __invoke ($request, $response, $next)
    {
        $response = $next($request, $response);

        // add logging of response here, after call to $next
        $this->container->logger->debug('Response status: ' . $response->getStatusCode());

        return $response;
    }
}
1 Like

Thank you, llvdl!
It’s works super fine.

Do you know how to get also the _POST parameters for logging?
Big thanks in advance.

Hello AndreiGOiN,

I think $request->getParsedBody() should work to get the post parameters. See https://www.slimframework.com/docs/objects/request.html#the-request-body

1 Like