Created
August 15, 2019 09:31
-
-
Save technoknol/6a8b9d88b243becaa057c080d6c49b87 to your computer and use it in GitHub Desktop.
Laravel – Log Guzzle requests to file (http://shyammakwana.me/laravel/laravel-log-guzzle-requests-to-file-using-service-container.html)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use GuzzleHttp\Client; | |
use GuzzleHttp\HandlerStack; | |
use GuzzleHttp\MessageFormatter; | |
use GuzzleHttp\Middleware; | |
use Illuminate\Support\ServiceProvider; | |
use Monolog\Handler\RotatingFileHandler; | |
use Monolog\Logger; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Bootstrap any application services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
$this->app->bind('GuzzleClient', function () { | |
$messageFormats = [ | |
'REQUEST: {method} - {uri} - HTTP/{version} - {req_headers} - {req_body}', | |
'RESPONSE: {code} - {res_body}', | |
]; | |
$stack = HandlerStack::create(); | |
collect($messageFormats)->each(function ($messageFormat) use ($stack) { | |
// We'll use unshift instead of push, to add the middleware to the bottom of the stack, not the top | |
$stack->unshift( | |
Middleware::log( | |
with(new Logger('guzzle-log'))->pushHandler( | |
new RotatingFileHandler(storage_path('logs/guzzle-log.log')) | |
), | |
new MessageFormatter($messageFormat) | |
) | |
); | |
}); | |
return function ($config) use ($stack){ | |
return new Client(array_merge($config, ['handler' => $stack])); | |
}; | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Route::get('/', function () { | |
$client = app('GuzzleClient')(['base_uri' => 'http://httpbin.org/']); | |
$request = $client->get('get',[ | |
'query' => ['foo'=>'bar', 'baz' => 'baz2'] , | |
'headers' => [ 'accept' => 'application/json'] | |
]); | |
$response = json_decode((string) $request->getBody()); | |
return response()->json($response); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment