【Laravel】api接口全局記錄日志


直接上代碼吧。全局路由中間件

<?php

namespace AppHttpMiddleware;



use Closure;
use IlluminateSupportFacadesDB;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesCache;

class ApiRoute
{   
    /**
     * 路由全局中間件
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $now_time = time();
        $date_now_time = date("Y-m-d H:i:s",$now_time);

        $user_id = 0;
        if(!empty($request->header('TOKEN'))){
            //得到userid
            $user_id = '';
        }

        $request->merge(['sq_time' => microtime(true)]);
        $response = $next($request);


        $rq_time = microtime(true)-$request->sq_time;
        //插入請求日志
        $request_url = $request->getRequestUri();
        
        DB::connection('mysql_log_config')
            ->table("request_log")
            ->insert([
                'user_id'=>$user_id,
                'header'=>json_encode($request->header()),
                'ip_address'=>$request->ip(),
                'method'=>$request->method(),
                'url'=>$request->fullUrl(),
                'param'=>json_encode($request->all()),
                'rq_time'=>sprintf("%.2f",$rq_time),
                'response'=>$response->getContent(),
                'created_at'=>$now_time,
                'updated_at'=>$now_time
            ]);

        return $response;
    }
}

SQL

CREATE TABLE `request_log` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL COMMENT '用戶ID',
  `header` longtext COMMENT '請求頭',
  `ip_address` varchar(255) DEFAULT NULL COMMENT '客戶端IP',
  `method` varchar(255) DEFAULT NULL COMMENT '請求方法',
  `url` varchar(255) DEFAULT NULL COMMENT '請求url',
  `param` longtext COMMENT '請求參數',
  `rq_time` float(10,2) DEFAULT NULL COMMENT '響應時間',
  `response` longtext COMMENT '響應結果',
  `created_at` int(10) DEFAULT NULL,
  `updated_at` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

轉載:https://www.cnblogs.com/richerdyoung/p/13841347.html

 

 

 

-----------------------------------------------------------------------------------------------

Laravel5.8 API 接口請求,出現問題,煩請指教

這個問題 百度上也沒有個方向是指,返回的數據必須是 response->json 不能是 json_encode ,
實際這個問題出現時 是 api 接口請求時出現的,也看到這個中間件時限制 api 請求頻率的,但是報的這個錯誤,確實不清楚怎么出現的 ,煩請各位不吝賜教!!!

中間件中不能用 json_encode
使用 return response ()->json (array ('code' => ErrorCode::NOT_LOGIN, 'msg' => ErrorMsg::$errorMsg [ErrorCode::NOT_LOGIN])); 就好了。
原文:https://blog.csdn.net/qq_32534555/article/...

————————————————
原文作者:FirstBlood
轉自鏈接:https://learnku.com/laravel/t/28552
版權聲明:著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請保留以上作者信息和原文鏈接。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM