nnt / activity-log

该包最新版本(dev-main)没有提供许可证信息。

此包提供易于使用的功能,以记录您应用程序用户的活动日志。

dev-main 2024-07-16 05:00 UTC

This package is not auto-updated.

Last update: 2024-09-25 04:03:03 UTC


README

安装

  1. 要安装本地路径的包,请运行以下命令

     composer require nnt/activity-log
    
  2. 发布配置

     php artisan vendor:publish --provider="NNT\ActivityLog\ActivityLogServiceProvider" --tag="config"
    
     php artisan config:cache
    
  3. 发布迁移

     php artisan vendor:publish --provider="NNT\ActivityLog\ActivityLogServiceProvider" --tag="migrations"
    
  4. 运行 php artisan migrate 在数据库中创建 activity_logs 表

使用说明

手动记录

要快速记录,可以使用

activity_log()->log('Hello World!');

一些高级功能

  1. 设置 log_type 列

    使用 logType 来设置 log_type 列的值

    activity_log()   
        ->logType($eventName)
        ->log('Hello World!');
  2. 设置 Subject 列

    使用 performedOn 来设置 subject 列的值。此列将存储要记录的对象的 id 和 model

    activity_log()   
        ->performedOn($anEloquentModel)
        ->log('Hello World!');
  3. 设置 Subject 列

    使用 causedBy 来设置 causer 列的值。此列将存储正在记录的用户 id 和 model

    activity_log()   
        ->causedBy($userEloquentModel)
        ->log('Hello World!');

    默认情况下,如果没有传入任何内容,将使用当前登录用户。

    如果留空此字段,则使用 causedByAnonymous

    activity_log()   
        ->causedByAnonymous()
        ->log('Hello World!');
  4. 设置 before_value 和 after_value 列

    使用 beforeValueafterValue 来设置这两个列的值,传入的参数是数组,数据将在存入数据库前进行 json_encode 编码

    activity_log()   
        ->beforeValue($beforeValue)
        ->afterValue($afterValue)
        ->log('Hello World!');
  5. 设置 description 列

    使用 log 来设置 description 列的值。此方法必须提供以保存数据

    activity_log()
        ->log('Hello World!');
  6. 设置 created_at 列

    使用 createdAt 来设置 created_at 列的值。传入的参数是 Carbon 对象

    activity_log()
        ->createdAt($timestamp)
        ->log('Hello World!');
  7. 要禁用当前请求的日志记录,则使用

    activity_log()->disableLogging();
  8. 要启用当前请求的日志记录,则使用

    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 文件