composer require vbukreyev/guzzle-log-middleware
use Concat\Http\Middleware\Logger;
You can use either a PSR-3 logger (such as Monolog) or a callable that accepts a log level, message, and context as an array.
$logger = new myLogger(); // should implements Psr\Log\LoggerInterface
$middleware = new Logger($logger);
$middleware->setLogLevel(LogLevel::DEBUG);
$middleware->setFormatter(new \GuzzleHttp\MessageFormatter(myLogger::MY_FORMAT));
$middleware->setRequestLoggingEnabled(false);
$stack = \GuzzleHttp\HandlerStack::create();
$stack->push($middleware->logHandler());
$client = new GuzzleHttp\Client([
'handler' => $stack,
]);
###
class myLogger extends \Psr\Log\AbstractLogger {
const MY_FORMAT = "{hostname} {req_header_User-Agent} - [{date_common_log}] \"{method} {target} HTTP/{version}\" {code} {res_header_Content-Length} :: {req_body}";
public function log($level, $message, array $context = array()) {
file_put_contents('/tmp/my-logger.log', $message . PHP_EOL, FILE_APPEND);
}
}
or
$middleware = new Logger(function ($level, $message, array $context) {
// Log the message
});
You can set a log level as a string or a callable that accepts a response. If the
response is not set, it can be assumed that it's a request-only log, or that the
request has been rejected. If the log level is not set, the default log level will be
used which is LogLevel::NOTICE
for status codes >= 400, or LogLevel::INFO
otherwise.
use Psr\Log\LogLevel;
$middleware->setLogLevel(LogLevel::DEBUG);
or
$middleware->setLogLevel(function ($response) {
// Return log level
});
You can set a message formatter as a MessageFormatter or a callable that accepts a request, response, as well as a reason when a request has been rejected.
$middleware->setFormatter($formatter);
or
$middleware->setFormatter(function ($request, $response, $reason) {
// Return log message
});
or
$middleware = new Logger($logger, $formatter);
A request will only be logged when its response is received. You can enable request logging
by using $middleware->setRequestLoggingEnabled(true)
, which will log a request when it is requested,
as well as its response when it is received. Any $response
references will be null
in the case
where only the request exists.
This package is designed to function as Guzzle 6 Middleware.