【Laravel】增加日志记录
生活随笔
收集整理的這篇文章主要介紹了
【Laravel】增加日志记录
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- Logs 表結構
- App\Models\Model\Logs
- App\Http\Middleware\OperationLogs 中間件
- app\Http\Kernel 注冊中間件
- 生成并優化自動加載文件
- Controller 獲取Log日志數據
Logs 表結構
App\Models\Model\Logs
<?php namespace App\Models;use App\Models\Model;/*** 日志表*/ class Logs extends Model {protected $connection = 'mysql';protected $table = "logs";protected $primaryKey = "id";public $timestamps = false;public function user(){return $this->belongsTo('App\User', 'uid', 'id');}/*** 根據路由,對各API 分組分類*/public static function apiStyle(){return [['label' => '全部','value' => '',],['label' => '設備','value' => 'device',],];}public function scopeSearchByPath($query, $path){if ($path != '') {$query->where(function ($query) use ($path) {$query->where("path", 'like', '%' . $path . '%');});}return $query;} }App\Http\Middleware\OperationLogs 中間件
此部分作用: 插入數據
<?phpnamespace App\Http\Middleware;use App\Models\Logs; use Auth; use Closure; use Illuminate\Http\Request;class OperationLogs {/*** Handle an incoming request.** @param \Illuminate\Http\Request $request* @param \Closure $next* @return mixed*/public function handle(Request $request, Closure $next){$request->setTrustedProxies($request->getClientIps());// $project = Auth::guard();$noRecordPath = ($request->path() != 'api/device/lists');$noGet = ('GET' != $request->method());if ($noGet && $noRecordPath) {$userId = !empty(auth('api')->check()) ? auth('api')->id() : 0;$input = $request->all();$log = new Logs();$log->uid = $userId;$log->path = $request->path();$log->method = $request->method();$log->ip = $request->getClientIp();$log->sql = '';$log->input = json_encode($input, JSON_UNESCAPED_UNICODE);$log->project = '';$log->created_at = date('Y-m-d H:m:s');$log->save(); // save log}return $next($request);} }app\Http\Kernel 注冊中間件
// 注意是路由的中間組,是屬于web,還是 api,請注意!!!protected $middlewareGroups = ['web' => [.....],'api' => ['throttle:60,1','bindings',\App\Http\Middleware\OperationLogs::class,],];生成并優化自動加載文件
執行 composer dump-autoload --optimize
Controller 獲取Log日志數據
<?phpnamespace App\Http\Controllers;use App\Models\Logs; use Illuminate\Http\Request;class LogsController extends CommonController {/*** Create a new controller instance.** @return void*/public function __construct(){@parent::__construct();$this->middleware('auth');}/*** 獲取操作日志信息*/public function ajaxGetLogsList(){$page = Request()->input('page', 1);$select = Request()->input('select');$list = Logs::with(['user'])->SearchByPath($select['path'])->forPage($page, $this->LIMIT)->orderBy('id', 'desc')->get();$total = Logs::SearchByPath($select['path'])->count('id');$data['list'] = $list;$data['total'] = $total;$data['limit'] = $this->LIMIT;$data['apiStyle'] = Logs::apiStyle();return $list ? $this->ajaxSuccess($data, "加載成功") : $this->ajaxFail($data, "暫無數據");} }總結
以上是生活随笔為你收集整理的【Laravel】增加日志记录的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Docker】备份Docker镜像im
- 下一篇: 【Linux】crontab 定时任务