Skip to content

Log HTTP web requests made from your application

License

Notifications You must be signed in to change notification settings

always-open/laravel-request-logger

Repository files navigation

Laravel Request Logger

Latest Version on Packagist Build Status GitHub Workflow Status (branch) Packagist Downloads

Maintainability

When making HTTP requests to external APIs it is valuable to track each request and its response. This insight can help you find issues, track usage, and reuse responses for testing/development.

Installation

You can install the package via composer:

composer require always-open/laravel-request-logger

Configuration

php artisan vendor:publish --provider="\AlwaysOpen\RequestLogger\RequestLoggerServiceProvider"

Running the above command will publish the config file.

Usage

Creation

To add logs to your system you must first create the migration and model for the appropriate log. This is done by using the packages request-logger:make-table command.

The command needs the name of the item to be tracked and it will be used for naming the model and table.

Example

php artisan request-logger:make-table facebook

This will create a model \App\Models\FacebookRequestLog and a migration to create the table facebook_request_logs

Implementation

Then you can use that model to create logs of your requests where you can make the API calls.

Example

Guzzle
function makeFacebookApiCall(array $body, Client $facebook_client)
{
    $request_headers = [
        'api-key' => $config->apiKey,
        'Content-Type' => 'application/json',
    ];

    $versioned_path = self::buildVersionedUrlPath($path);

    $encoded_body = json_encode($body, JSON_UNESCAPED_SLASHES);

    $request = new Request(
        'GET',
        '/v1/users',
        $request_headers,
        $encoded_body,
    );
    
    $request_log = FacebookRequestLog::makeFromGuzzle($request);
    
    $response = $client->send($request);
    
    $request_log->response_code = $response->getStatusCode();
    $request_log->response = json_decode((string)$response->getBody(), true);
    $request_log->save();
}

You can also manually set each property and then save the log instance.

Testing

composer test

Using Docker

All assets are set up under the docker-compose.yml file. The first time you run the docker image you must build it with the following command:

./docker.sh -b -s

Then you can bring it up in the background using:

./docker.sh -d

From there you can run the tests within an isolated environment

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email @qschmick instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.