laravel中通过fileauditevent事件与logfileaudit监听器实现文件操作审计,异步写入fileauditlog模型,记录操作人、时间、路径、上下文等信息,敏感字段过滤后存入innodb表。

在Laravel项目中记录用户对文件的上传、下载、删除、重命名等操作,需精确捕获操作人、时间、文件路径、原始名称、目标路径及HTTP上下文(如IP、UA),避免日志遗漏或敏感信息泄露。
定义审计事件与监听器
创建 FileAuditEvent 事件类,携带操作类型(upload/delete/rename/download)、文件元数据及请求上下文。
运行 php artisan make:event FileAuditEvent,在构造函数中接收 $user、$operation、$file(SplFileInfo 或数组)、$request(可选)。
执行 php artisan make:listener LogFileAudit --event=FileAuditEvent,在 handle() 方法中调用审计日志写入逻辑,不直接写入数据库,而是交由队列异步处理。
构建审计日志模型与迁移
运行 php artisan make:model Models/FileAuditLog -m,在迁移文件中添加字段:user_id(nullable)、operation(enum: upload,delete,rename,download)、original_name(string)、path(text)、new_path(text, nullable)、ip_address(string)、user_agent(text)、context(json,存 request()->except(['_token','_method']) 等非敏感键)、created_at。
【migration 中必须设置 $table->engine = 'InnoDB';】 否则 JSON 字段在 MySQL 5.7+ 以下版本会报错。
运行 php artisan migrate 完成表创建。
实现异步日志写入逻辑
在 app/Listeners/LogFileAudit.php 的 handle() 方法中:
① 提取 $event->user->id ?? null,若为 null 则跳过写入(如 CLI 触发或未登录访问);
② 使用 request()->ip() 和 request()->userAgent() 获取客户端信息;
③ 对 $event->file 进行标准化:若为 SplFileInfo,取 getRealPath() 和 getFilename();若为数组(如多文件上传),遍历生成多条日志;
④ 构建 FileAuditLog::create([...]) 数据,其中 context 字段只保留 request()->only(['url', 'method', 'query', 'post']),排除 headers、cookies、files 等敏感内容;
⑤ 将该 create 操作包裹在 dispatch(new LogFileAuditJob(...)) 队列任务中,确保高并发下不阻塞主流程。
在文件操作处触发审计事件
方法一:在控制器中手动触发
上传后: event(new FileAuditEvent(auth()->user(), 'upload', $uploadedFile, request()));
删除前: event(new FileAuditEvent(auth()->user(), 'delete', ['path' => $diskPath, 'original_name' => $name], request()));
方法二:使用 Laravel 文件系统事件钩子(仅适用于 Storage::put / delete 等标准方法)
在 AppServiceProvider@boot 中注册监听:Storage::extend('audit', function ($app, $config) { ... }); 不推荐——会干扰原有驱动行为。
方法三:封装自定义文件服务类(推荐)
新建 app/Services/FileAuditService.php,提供 upload()、delete()、rename() 方法,在每个方法末尾调用 event(new FileAuditEvent(...)),业务代码统一调用该服务而非原生 Storage facade。
【务必在 rename() 中同时传入 old_path 和 new_path,并设为 new_path 字段值】 否则重命名操作无法体现目标位置变更。











