利用Laravel中间件给后台加个操作日志

项目后台角色及人员变多,需要加下日志,方便查询,不妨利用中间件实现下。

方案:

  • 中间件判断是否需要记录,写入队列
  • 队列写入数据库

表设计

1
2
3
4
5
6
7
8
9
10
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,在后台路由中加入此中间件即可,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?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);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?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);
}
}

执行队列:

1
php artisan queue:work --queue=adminLog

当然,也可以不写入数据库,写在log文件里,这里就不展开了。

另外,为了方便,也可以给后台统一加入AdminLogMiddleware中间件,把不需要做记录的路由加入配置文件,在中间件加入判断,省去在路由配置去区分是否需要记录。