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$response
variable.
Helpful links
More of Php Guzzle
- How to set a user agent in PHP Guzzle?
- How to set a timeout for a request with PHP Guzzle?
- How to add an SSL certificate to a request with PHP Guzzle?
- How to handle a RequestException with PHP Guzzle?
- How to make an asynchronous send with PHP Guzzle?
- How to convert a response to an array with PHP Guzzle?
- What version of PHP is required for Guzzle?
- How to make HTTP request with PHP Guzzle?
- How to stream with PHP Guzzle?
- How to troubleshoot cURL error 60 with Guzzle in PHP?
See more codes...