nnt / activity-log
此包提供易于使用的功能,以记录您应用程序用户的活动日志。
This package is not auto-updated.
Last update: 2024-09-25 04:03:03 UTC
README
安装
-
要安装本地路径的包,请运行以下命令
composer require nnt/activity-log
-
发布配置
php artisan vendor:publish --provider="NNT\ActivityLog\ActivityLogServiceProvider" --tag="config" php artisan config:cache
-
发布迁移
php artisan vendor:publish --provider="NNT\ActivityLog\ActivityLogServiceProvider" --tag="migrations"
-
运行 php artisan migrate 在数据库中创建 activity_logs 表
使用说明
手动记录
要快速记录,可以使用
activity_log()->log('Hello World!');
一些高级功能
-
设置 log_type 列
使用
logType
来设置 log_type 列的值activity_log() ->logType($eventName) ->log('Hello World!');
-
设置 Subject 列
使用
performedOn
来设置 subject 列的值。此列将存储要记录的对象的 id 和 modelactivity_log() ->performedOn($anEloquentModel) ->log('Hello World!');
-
设置 Subject 列
使用
causedBy
来设置 causer 列的值。此列将存储正在记录的用户 id 和 modelactivity_log() ->causedBy($userEloquentModel) ->log('Hello World!');
默认情况下,如果没有传入任何内容,将使用当前登录用户。
如果留空此字段,则使用
causedByAnonymous
activity_log() ->causedByAnonymous() ->log('Hello World!');
-
设置 before_value 和 after_value 列
使用
beforeValue
和afterValue
来设置这两个列的值,传入的参数是数组,数据将在存入数据库前进行 json_encode 编码activity_log() ->beforeValue($beforeValue) ->afterValue($afterValue) ->log('Hello World!');
-
设置 description 列
使用
log
来设置 description 列的值。此方法必须提供以保存数据activity_log() ->log('Hello World!');
-
设置 created_at 列
使用
createdAt
来设置 created_at 列的值。传入的参数是 Carbon 对象activity_log() ->createdAt($timestamp) ->log('Hello World!');
-
要禁用当前请求的日志记录,则使用
activity_log()->disableLogging();
-
要启用当前请求的日志记录,则使用
activity_log()->enableLogging();
模型事件日志
此包可用于自动记录模型事件
要使用,请在模型中添加 LogsActivity
trait
use NNT\ActivityLog\Traits\LogsActivity; class NewsItem extends Model { use LogsActivity; }
默认为 ['created', 'updated', 'deleted']
,如果使用了 SoftDelete trait,则还支持一个额外的事件 ['restored']
要指定哪些模型事件需要记录,则在模型中添加 $recordEvents
protected static $recordEvents = ['deleted'];
要指定哪些属性更改不会触发日志事件,则使用
protected static $ignoreChangedAttributes = ['text'];
默认情况下,updated_at
不会被忽略,因此在更新数据时将触发。如果要忽略此操作,则将其放入 $ignoreChangedAttributes
要从不记录的值中排除属性,则使用
protected static $logAttributesToIgnore = ['password', 'updated_at'];
要自定义描述,请在模型中使用 customActivityDescription()
方法。此方法将允许在将其存储到数据库之前修改描述
示例
public function customActivityDescription($model, string $eventName) { if ($model->wasChanged('password')) { return 'Password has changed'; } return __("activity_log::messages.{$eventName}"); }
要强制设置 related_type 列,请在模型中添加 $relatedType
protected static $relatedType = 'User';
如果没有设置此值,则 related_type 列将以 PascalCase 格式添加,并使用单数形式(Job, Customer,...)
高级配置
可以在配置文件中设置一些功能。有关详细信息,请参阅 activity-log.php 文件