php-guzzleHow to use Monolog with Guzzle in PHP?
Monolog is a logging library for PHP which can be used with Guzzle to log requests and responses.
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('guzzle');
$logger->pushHandler(new StreamHandler('/path/to/your.log', Logger::DEBUG));
$client = new GuzzleHttp\Client([
'base_uri' => 'http://httpbin.org',
'handler' => GuzzleHttp\HandlerStack::create(
new GuzzleHttp\Handler\CurlHandler(),
new GuzzleHttp\Handler\LoggingHandler($logger)
)
]);
$response = $client->get('/get');
The output of the example code will be a log file containing the request and response information.
Code explanation
-
use Monolog\Logger;anduse Monolog\Handler\StreamHandler;- These lines import the Monolog library and the StreamHandler class. -
$logger = new Logger('guzzle');- This line creates a new Logger instance with the name 'guzzle'. -
$logger->pushHandler(new StreamHandler('/path/to/your.log', Logger::DEBUG));- This line adds a StreamHandler to the Logger instance, which will write the log messages to the specified file. -
new GuzzleHttp\Handler\LoggingHandler($logger)- This line creates a LoggingHandler instance which will use the Logger instance to log the requests and responses. -
$client = new GuzzleHttp\Client([...])- This line creates a new Guzzle client with the LoggingHandler added to the handler stack. -
$response = $client->get('/get');- This line sends a GET request to httpbin.org and stores the response in the$responsevariable.
Helpful links
More of Php Guzzle
- How to set a user agent in PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
- PHP Guzzle usage example
- How to use PHP Guzzle to make a batch request?
- How to add a bearer token in PHP Guzzle?
- How to stream with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to retry requests with PHP Guzzle?
- How to use Promises with PHP Guzzle (with an example)?
See more codes...