PHP
Logging middleware
Learn to write a logging middleware that records requests.
Logging middleware
A logging middleware records every request that arrives. It writes information such as method, path, duration, and response code to a file or to standard output. It is essential for debugging and audit trails.
The typical pattern: print the request with echo "[LOG] {$request}\n"; and then continue the flow with return $next($request);. The next layers still run, and the request is recorded too.
Place logging on the outer edge of the pipeline to observe the full lifecycle of the request, both before and after phases.
Log format
The log line should follow a consistent format. A common pattern: [LOG] {method} {path}. For more detail you can use sprintf to write method, path and status into one line.
To measure duration, call microtime(true) in the before and after phases; the difference is logged in milliseconds. This helps find slow routes.
To print the request on a single line, echo "[LOG] {$request}\n"; is enough. Inside double quotes, curly braces expand variables.
Exercise Write a requestLogger
Define a requestLogger($request, $next) function. Inside it, print the request with echo "[LOG] " . $request . "\n", then continue the flow with return $next($request). The $handler returns "ok". Call it with two different requests and print the results: "GET /a" and "POST /b".
Show example solution
Write function requestLogger($request, $next) { echo "[LOG] " . $request . "\n"; return $next($request); }. Then echo requestLogger("GET /a", $handler) . "\n"; and echo requestLogger("POST /b", $handler) . "\n";.
Example solution:
<?php
function requestLogger($request, $next) {
echo "[LOG] " . $request . "\n";
return $next($request);
}
$handler = function ($request) {
return "ok";
};
echo requestLogger("GET /a", $handler) . "\n";
echo requestLogger("POST /b", $handler) . "\n";
Test yourself
-
Match the log components
- method
- GET, POST
- path
- /users, /api
- status
- 200, 404
- body
- Response content
-
When does a logging middleware run?
- Only on errors
- Only for logged in users
- Only on weekends
- On every request
Show answer
On every request — Correct. A logging middleware runs on every request; it keeps a consistent audit trail.
-
Log the request
echo "[LOG] " . ____ . "
";
Show answer
echo "[LOG] " . $request . "
";
Next lesson: PSR-15 basics