Created
March 1, 2020 08:46
-
-
Save Cannonb4ll/2cd7fff9d72927b0cb8aa689b211a5e3 to your computer and use it in GitHub Desktop.
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 | |
namespace App\Http\Middleware\Api; | |
use Closure; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Redis; | |
class TrackApiStatistics | |
{ | |
/** | |
* The attributes that should not be included in logging | |
* | |
* @var array | |
*/ | |
protected $stripHeaders = [ | |
'authorization' | |
]; | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* | |
* @return mixed | |
*/ | |
public function handle(Request $request, Closure $next) | |
{ | |
try { | |
/* @var $connection \Predis\ClientInterface */ | |
$connection = Redis::connection('api'); | |
$connection->incr('total_calls'); | |
$key = str_slug('request_' . date('YmdHis'), '_'); | |
$connection->hset($key, 'url', $request->fullUrl()); | |
$connection->hset($key, 'headers', serialize($this->filterHeaders($request->headers->all()))); | |
$connection->hset($key, 'method', $request->method()); | |
$connection->hset($key, 'payload', serialize($request->input())); | |
$connection->hset($key, 'ip', $request->ip()); | |
} catch (\Exception $exception) { | |
} | |
return $next($request); | |
} | |
public function filterHeaders(array $headers = []) | |
{ | |
foreach ($headers as $key => $header) { | |
if (in_array($key, $this->stripHeaders)) { | |
unset($headers[$key]); | |
} | |
} | |
return $headers; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment