需求
在尚未有任何 GUI畫面或 API Response之前,如果想要知道每一個router路徑到底傳入什麼、輸出了什麼,可透過建立 Before and After Middleware 來實現。
php artisan make:middleware apiLog
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
//新增剛剛的
\App\Http\Middleware\apiLog::class,
];
class apiLog
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$fromIP = $request->ip();
$uri = $request->path();
$method = $request->method();
$body = $request->all();
$logResquest = [
'fromIP: ' => $fromIP,
'uri: '=> $uri,
'method: '=>$method,
'details:'=>$body
];
Log::notice("request ", $logResquest);
$response = $next($request);
$body = $response->content();
$logResponse = [
'fromIP: ' => $fromIP,
'uri: '=>$uri,
'details:'=>$body
];
Log::notice("response ", $logResponse);
return $response;
}
}
The key difference is in how the $request parameter is handled. If actions are performed before $next($request) that will happen before the controller code is executed while calling $next($request) first will lead to the actions being performed after the controller code is executed
public function handle($request, Closure $next)
{
// before middleware workspace
$response = $next($request);
// after middleware workspace
return $response;
}
API 實測
log紀錄內容
可看到Log裡頭有request、response的傳輸資訊,這些內容會紀錄超文本傳輸時所轉換的文字格式。
參考資料
https://laravel.tw/docs/5.2/requests
https://ithelp.ithome.com.tw/articles/10208371
https://riptutorial.com/laravel/example/16346/before-vs--after-middleware
https://zh.wikipedia.org/wiki/%E8%B6%85%E6%96%87%E6%9C%AC%E4%BC%A0%E8%BE%93%E5%8D%8F%E8%AE%AE