Skip to content

Commit bf94fbe

Browse files
committed
Initial commit
0 parents  commit bf94fbe

18 files changed

+959
-0
lines changed

.gitattributes

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Auto detect text files and perform LF normalization
2+
* text=auto

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
composer.lock
2+
vendor
3+
.DS_Store

.phpunit.result.cache

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"version":1,"defects":{"RequestResponseLoggerTest::canInstantiateClass":4,"RequestResponseLoggerTest::canInstantiateClassFromHelper":4,"RequestResponseLoggerTest::canInstantiateClassFromFacade":4,"RequestResponseLoggerTest::canSetNewEndPoint":4,"RequestResponseLoggerTest::canSwitchEnvironment":4,"RequestResponseLoggerTest::canGetVendorThroughCallMethod":4,"RequestResponseLoggerTest::canSkipParametersMethod":4,"RequestResponseLoggerTest::canGetVendorThroughMagicMethod":4,"RequestResponseLoggerTest::middlewareSavesALog":4,"RequestResponseLoggerTest::middlewareSavesHeaderData":4,"RequestResponseLoggerTest::middlewareRetrievesHeaderDataAsObject":5,"RequestResponseLoggerTest::middlewareRetrievesDataAsObject":4,"RequestResponseLoggerTest::middlewareSavesAGetRequest":4,"RequestResponseLoggerTest::middlewareSavesAPostRequest":4,"RequestResponseLoggerTest::middlewareSavesPostData":4,"RequestResponseLoggerTest::middlewareSavesJsonPostData":4,"RequestResponseLoggerTest::middlewareRetrievesJsonAsObject":4,"RequestResponseLoggerTest::middlewareSavesXmlRequestData":4,"RequestResponseLoggerTest::modelSuccessfulScopeWorks":4,"RequestResponseLoggerTest::middlewareSavesXmlPostData":4,"RequestResponseLoggerTest::modelFailedScopeWorks":4},"times":{"RequestResponseLoggerTest::canInstantiateClass":0.078,"RequestResponseLoggerTest::canInstantiateClassFromHelper":0.004,"RequestResponseLoggerTest::canInstantiateClassFromFacade":0.003,"RequestResponseLoggerTest::canSetNewEndPoint":0.003,"RequestResponseLoggerTest::canSwitchEnvironment":0.003,"RequestResponseLoggerTest::canGetVendorThroughCallMethod":0.003,"RequestResponseLoggerTest::canSkipParametersMethod":0.003,"RequestResponseLoggerTest::canGetVendorThroughMagicMethod":0.003,"RequestResponseLoggerTest::middlewareSavesALog":0.12,"RequestResponseLoggerTest::middlewareSavesAGetRequest":0.299,"RequestResponseLoggerTest::middlewareSavesAPostRequest":0.008,"RequestResponseLoggerTest::middlewareSavesPostData":0.008,"RequestResponseLoggerTest::middlewareSavesHeaderData":0.008,"RequestResponseLoggerTest::middlewareSavesJsonPostData":0.007,"RequestResponseLoggerTest::middlewareRetrievesHeaderDataAsObject":0.008,"RequestResponseLoggerTest::middlewareRetrievesDataAsObject":0.007,"RequestResponseLoggerTest::middlewareRetrievesJsonAsObject":0.008,"RequestResponseLoggerTest::middlewareSavesXmlRequestData":0.008,"RequestResponseLoggerTest::middlewareSavesXmlPostData":0.009,"RequestResponseLoggerTest::modelSuccessfulScopeWorks":0.007,"RequestResponseLoggerTest::modelFailedScopeWorks":0.007}}

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2021 Mark
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

LICENSE.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) Mark Townsend <mtownsend5512@gmail.com>
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in
13+
all copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
THE SOFTWARE.

README.md

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
<p align="center">
2+
<img src="https://banners.beyondco.de/Laravel%20Request%20%26%20Response%20Logger.png?theme=dark&packageManager=composer+require&packageName=mtownsend%2Flaravel-request-response-logger&pattern=plus&style=style_1&description=Capture+your+incoming+requests+and+corresponding+responses+with+ease&md=1&showWatermark=0&fontSize=75px&images=https%3A%2F%2Flaravel.com%2Fimg%2Flogomark.min.svg">
3+
</p>
4+
5+
Easily capture every incoming request and the corresponding outgoing response in your Laravel app.
6+
7+
*This package is designed to work only with the Laravel framework.*
8+
9+
## Installation
10+
11+
Install via composer:
12+
13+
```
14+
composer require mtownsend/laravel-request-response-logger
15+
```
16+
17+
### Registering the service provider (Laravel users)
18+
19+
For Laravel 5.4 and lower, add the following line to your ``config/app.php``:
20+
21+
```php
22+
/*
23+
* Package Service Providers...
24+
*/
25+
Mtownsend\RequestResponseLogger\Providers\RequestResponseLoggerServiceProvider::class,
26+
```
27+
28+
For Laravel 5.5 and greater, the package will auto register the provider for you.
29+
30+
31+
### Publish the migration and config files
32+
33+
You will need to publish the migration and configuration file before you can begin using the package. To do so run the following in your console:
34+
35+
````
36+
php artisan vendor:publish --provider="Mtownsend\RequestResponseLogger\Providers\RequestResponseLoggerServiceProvider"
37+
````
38+
39+
Next, you need to run the migration for the new database table. Run the following in your console:
40+
41+
````
42+
php artisan migrate
43+
````
44+
45+
### Setting up the middleware (important!)
46+
47+
In order to begin logging requests and responses you will have to attach the middleware to the routes you want to log. The package *does not* make this assumption for you, since not everyone may want to log every route.
48+
49+
Now, navigate to your `/app/Http/Kernel.php`
50+
51+
You can choose which method you would like to use. We've provided a few different options below:
52+
53+
#### OPTION 1: Bind the middleware to a name you can call only on the routes you want
54+
55+
```php
56+
protected $routeMiddleware = [
57+
...
58+
'log.requests.responses' => \Mtownsend\RequestResponseLogger\Middleware\LogRequestsAndResponses::class,
59+
];
60+
```
61+
62+
Then apply the named middleware to whatever routes you want:
63+
64+
```php
65+
Route::post('/some/route', SomeController::class)->middleware(['log.requests.responses']);
66+
```
67+
68+
#### OPTION 2: Assign the middleware to a route group
69+
70+
```php
71+
protected $middlewareGroups = [
72+
...
73+
'api' => [
74+
...
75+
\Mtownsend\RequestResponseLogger\Middleware\LogRequestsAndResponses::class,
76+
],
77+
];
78+
```
79+
80+
#### OPTION 3: Assign the middleware to every route
81+
82+
```php
83+
protected $middleware = [
84+
...
85+
\Mtownsend\RequestResponseLogger\Middleware\LogRequestsAndResponses::class,
86+
];
87+
```
88+
89+
That's it! The middleware will log every incoming request it receives!
90+
91+
### Customizing your configuration (optional)
92+
93+
This package provides a few customizations you can make.
94+
95+
When you navigation to `app/config` you will see a `log-requests-and-responses.php` file. It will contain the following:
96+
97+
```php
98+
return [
99+
100+
/**
101+
* The model used to manage the database table for storing request and response logs.
102+
*/
103+
'logging_model' => \Mtownsend\RequestResponseLogger\Models\ArrayOrText::class,
104+
105+
/**
106+
* When logging requests and responses, should the logging action be
107+
* passed off to the queue (true) or run synchronously (false)?
108+
*/
109+
'logging_should_queue' => false,
110+
111+
/**
112+
* If stored json should be transformed into an array when retrieved from the database.
113+
* Set to `false` to receive as a regular php object.
114+
*/
115+
'get_json_values_as_array' => true,
116+
117+
];
118+
```
119+
120+
## Housekeeping
121+
122+
You may want to utilize some housekeeping to prevent your logs table from getting too large. This package supplies a preregistered command for wiping the table clean. You may run it manually
123+
124+
````
125+
php artisan request-response-logger:clean
126+
````
127+
128+
You may also schedule it to be run automatically in `app/Console/Kernel.php`:
129+
130+
```php
131+
protected function schedule(Schedule $schedule)
132+
{
133+
...
134+
$schedule->command('request-response-logger:clean')->quarterly();
135+
}
136+
```
137+
138+
## Advanced Usage
139+
140+
## Model scopes
141+
142+
If you would like to work with the data you've logged, you may want to retrieve data based on the http code your app returned for that request.
143+
144+
```php
145+
use Mtownsend\RequestResponseLogger\Models\RequestResponseLog;
146+
147+
// Get every logged item with an http response code of 2XX:
148+
RequestResponseLog::successful()->get();
149+
150+
// Get every logged item with an http response code that ISN'T 2XX:
151+
RequestResponseLog::failed()->get();
152+
```
153+
154+
## Replacing the `RequestResponseLog` model with your own
155+
156+
You may want to extend the base `RequestResponseLog` model with your own. This is entirely possible.
157+
158+
First, create your own model
159+
160+
````
161+
php artisan make:model RequestResponseLog
162+
````
163+
164+
Then in your model, extend the base model:
165+
166+
```php
167+
<?php
168+
169+
namespace App\Models;
170+
171+
use Illuminate\Database\Eloquent\Factories\HasFactory;
172+
use Mtownsend\RequestResponseLogger\Models\RequestResponseLog as BaseRequestResponseLog;
173+
174+
class RequestResponseLog extends BaseRequestResponseLog
175+
{
176+
use HasFactory;
177+
}
178+
```
179+
180+
Then in your `app/config/log-requests-and-responses.php`:
181+
182+
```php
183+
'logging_model' => \App\Models\RequestResponseLog::class,
184+
```
185+
186+
Now the package will utilize your model instead of the default one.
187+
188+
189+
## Testing
190+
191+
You can run the tests with:
192+
193+
```bash
194+
vendor/bin/phpunit
195+
```
196+
197+
## License
198+
199+
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

composer.json

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
{
2+
"name": "mtownsend/laravel-request-response-logger",
3+
"description": "Easily capture every incoming request and the corresponding outgoing response in your Laravel app.",
4+
"keywords": [
5+
"request",
6+
"response",
7+
"logging",
8+
"debugging"
9+
],
10+
"license": "MIT",
11+
"authors": [
12+
{
13+
"name": "Mark Townsend",
14+
"email": "mtownsend5512@gmail.com",
15+
"role": "Developer"
16+
}
17+
],
18+
"autoload": {
19+
"psr-4": {
20+
"Mtownsend\\RequestResponseLogger\\": "src"
21+
},
22+
"files": []
23+
},
24+
"repositories": [],
25+
"require": {
26+
"php": ">=7.0|^8.0"
27+
},
28+
"require-dev": {
29+
"phpunit/phpunit": "^9.5",
30+
"orchestra/testbench": "^6.17"
31+
},
32+
"autoload-dev": {
33+
"psr-4": {
34+
"Mtownsend\\RequestResponseLogger\\Test\\": "tests/"
35+
}
36+
},
37+
"scripts": {
38+
"post-autoload-dump": [
39+
"@php ./vendor/bin/testbench package:discover --ansi"
40+
]
41+
},
42+
"extra": {
43+
"laravel": {
44+
"providers": [
45+
"Mtownsend\\RequestResponseLogger\\Providers\\RequestResponseLoggerServiceProvider"
46+
]
47+
}
48+
},
49+
"minimum-stability": "dev"
50+
}

phpunit.xml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="vendor/autoload.php" backupGlobals="false" backupStaticAttributes="false" colors="true" verbose="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
3+
<coverage>
4+
<include>
5+
<directory suffix=".php">src/</directory>
6+
</include>
7+
</coverage>
8+
<testsuites>
9+
<testsuite name="Mtownsend">
10+
<directory>tests</directory>
11+
</testsuite>
12+
</testsuites>
13+
</phpunit>

src/Casts/ArrayOrText.php

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
<?php
2+
3+
namespace Mtownsend\RequestResponseLogger\Casts;
4+
5+
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
6+
7+
class ArrayOrText implements CastsAttributes
8+
{
9+
/**
10+
* Cast the given value.
11+
*
12+
* @param \Illuminate\Database\Eloquent\Model $model
13+
* @param string $key
14+
* @param mixed $value
15+
* @param array $attributes
16+
* @return mixed
17+
*/
18+
public function get($model, $key, $value = null, $attributes = [])
19+
{
20+
if ($this->isJson($value)) {
21+
$value = json_decode($value, config('log-requests-and-responses.get_json_values_as_array'));
22+
}
23+
return $value;
24+
}
25+
26+
/**
27+
* Prepare the given value for storage.
28+
*
29+
* @param \Illuminate\Database\Eloquent\Model $model
30+
* @param string $key
31+
* @param mixed $value
32+
* @param array $attributes
33+
* @return mixed
34+
*/
35+
public function set($model, $key, $value = null, $attributes = [])
36+
{
37+
if (is_array($value)) {
38+
$value = json_encode($value);
39+
}
40+
return $value;
41+
}
42+
43+
/**
44+
* Checks if the string is valid json.
45+
*
46+
* @param string $string
47+
* @return boolean
48+
*/
49+
public function isJson($string)
50+
{
51+
json_decode($string);
52+
return json_last_error() === JSON_ERROR_NONE;
53+
}
54+
}

0 commit comments

Comments
 (0)