Skip to content

Instantly share code, notes, and snippets.

@Cannonb4ll
Created March 1, 2020 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cannonb4ll/2cd7fff9d72927b0cb8aa689b211a5e3 to your computer and use it in GitHub Desktop.
Save Cannonb4ll/2cd7fff9d72927b0cb8aa689b211a5e3 to your computer and use it in GitHub Desktop.
<?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