Skip to content

Instantly share code, notes, and snippets.

@ahsankhatri
Last active August 14, 2018 03:40
Show Gist options
  • Save ahsankhatri/a1bdf8ee8e884fd20ee37dc2730a9619 to your computer and use it in GitHub Desktop.
Save ahsankhatri/a1bdf8ee8e884fd20ee37dc2730a9619 to your computer and use it in GitHub Desktop.
Laravel 5.0~5.4 Webservice Logger. Log all request and response through middleware in wrapped routes

Webservice Logger for Laravel 5.0~5.4 (Haven't tested on 5.5+)

Log all request and response through middleware in api wrapped group routes.

Guide

wrap middleware in api group in app/Http/Kernel.php

    'api' => [
        'throttle:60,1',
        \App\Http\Middleware\WebserviceLogger::class,
    ],

Your routes should be wrapped in app/Http/routes.php like this:

Route::group(['middleware' => ['api'], 'prefix' => 'api'], function () {
    Route::post('register', 'ApiController@register');
    Route::post('login', 'ApiController@login');
});

Note: You can use LOG_WEBSERVICE as a boolean in .env in order to log under specified environment.

<?php
namespace App\Http\Middleware;
use Closure;
class WebserviceLogger
{
/**
* This will tell where to extract data from
*/
private static $loggerType = null;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $loggerType='json')
{
static::$loggerType = $loggerType;
return $next($request);
}
public function terminate($request, $response)
{
if ( env('LOG_WEBSERVICE', true) ) {
$filename = 'webservice_' . date('d-m-y') . '.log';
if ( static::$loggerType == 'json' && method_exists($response, 'getData') ) {
$output = (array) $response->getData();
if ( is_array($output) )
$output = json_encode($output);
} else if ( static::$loggerType == 'content' ) {
$output = $response->getContent();
} else {
return;
}
$inputExcept = [
// 'password',
// 'credit_card',
];
$input = [];
foreach ($request->request->all() as $key => $value) {
$input[$key] = $value;
if (in_array($key, $inputExcept)) {
$input[$key] = '********';
}
}
$dataToLog = '[' . \Carbon\Carbon::now()->toDateTimeString() . "] log.DEBUG: ";
$dataToLog .= 'Time: ' . gmdate("F j, Y, g:i a") . "\n";
$dataToLog .= 'URL: ' . $request->fullUrl() . "\n";
$dataToLog .= 'Method: ' . $request->method() . "\n";
$dataToLog .= 'Input: ' . print_r((array) $input, true) . "\n";
$dataToLog .= 'Output: ' . $output . "\n";
// Finally write log
\File::append( storage_path('logs' . DIRECTORY_SEPARATOR . $filename), $dataToLog . "\n" . str_repeat("=", 20) . "\n\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment