專案後臺角色及人員變多,需要加下日誌,方便查詢,不妨利用中介軟體實現下。
方案:
- 中介軟體判斷是否需要記錄,寫入佇列
- 佇列寫入資料庫
表設計
CREATE TABLE `admin_log` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`path` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`method` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
`ip` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`input` text COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
新建中介軟體AdminLogMiddleware,在後臺路由中加入此中介軟體即可,
<?php
/**
* Author: sai
* Date: 2020/4/1
* Time: 16:19
*/
namespace App\Http\Middleware;
use App\Jobs\OperationLogJob;
use Closure;
use Auth;
class AdminLogMiddleware
{
/**
* 處理傳入的引數
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string $role
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
// 剔除GET,OPTIONS請求
if (!in_array($method = $request->getMethod(), ['GET', 'OPTIONS'])) {
$data = [
'user_id' => Auth::guard('admin')->id(),
'path' => $request->getPathInfo(),
'method' => $method,
'ip' => $request->getClientIp(),
'input' => \json_encode($request->all(), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE),
];
// 非同步寫入,提高操作流暢性
$job = (new OperationLogJob($data));
dispatch($job);
}
return $next($request);
}
}
<?php
namespace App\Jobs;
use App\Models\AdminLog;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class OperationLogJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($data)
{
//
$this->queue = 'adminLog';
$this->data = $data;
}
private $data;
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
//
AdminLog::create($this->data);
}
}
執行佇列:
php artisan queue:work --queue=adminLog
當然,也可以不寫入資料庫,寫在log檔案裡,這裡就不展開了。
另外,為了方便,也可以給後臺統一加入AdminLogMiddleware中介軟體,把不需要做記錄的路由加入配置檔案,在中介軟體加入判斷,省去在路由配置去區分是否需要記錄。
本作品採用《CC 協議》,轉載必須註明作者和本文連結