sdon2/laravel-audit-log

一个用于监控您网站或应用程序用户的非常简单的审计日志器

v1.01 2022-07-29 06:21 UTC

This package is auto-updated.

Last update: 2024-09-29 06:20:30 UTC


README

sdon2/laravel-audit-log 包提供易于使用的函数来记录您的应用程序用户的操作。它还可以自动记录模型事件。所有活动都将存储在 audit_logs 表中。

AuditLogger::log('Look, I logged something');

您可以使用 Sdon2\Auditlog\Models\AuditLog 模型检索所有活动。

AuditLog::all();

以下是一个更高级的例子

AuditLogger::performedOn($anEloquentModel)
   ->causedBy($user)
   ->withProperties(['customProperty' => 'customValue'])
   ->log('Look, I logged something');
   
$lastLoggedAudit = AuditLog::all()->last();

$lastLoggedAudit->subject; //returns an instance of an eloquent model
$lastLoggedAudit->causer; //returns an instance of your user model
$lastLoggedAudit->getExtraProperty('customProperty'); //returns 'customValue'
$lastLoggedAudit->description; //returns 'Look, I logged something'
$newsItem->name = 'updated name';
$newsItem->save();

//updating the newsItem will cause an activity being logged
$auditLog = AuditLog::all()->last();

$auditLog->description; //returns 'updated'
$auditLog->subject; //returns the instance of NewsItem that was created

调用 $auditLog->changes 将返回此数组

[
   'attributes' => [
        'name' => 'updated name',
        'text' => 'New Text',
    ],
    'old' => [
        'name' => 'original name',
        'text' => 'Old text',
    ],
];

安装

您可以通过 composer 安装此包

composer require sdon2/laravel-audit-log

对于 laravel 8 是可选的

接下来,您必须安装服务提供者

// config/app.php
'providers' => [
    ...
    Sdon2\AuditLog\AuditLogServiceProvider::class,
];

您可以使用以下命令发布迁移

php artisan vendor:publish --provider="Sdon2\AuditLog\AuditLogServiceProvider" --tag="migrations"

注意:默认迁移假定您正在使用整数作为模型 ID。如果您正在使用 UUID 或其他格式,请在继续之前调整已发布迁移中 subject_id 和 causer_id 字段的格式。

迁移发布后,您可以通过运行迁移来创建 audit-logs

php artisan migrate

您可以选择使用以下命令发布配置文件

php artisan vendor:publish --provider="Sdon2\AuditLog\AuditLogServiceProvider" --tag="config"

这是已发布配置文件的内容

return [
    /**
     * When user visit every url update audit log
     */
    'record_visiting' => false,

    /*
     * If set to false, no audits will be saved to the database.
     */
    'enabled' => env('AUDIT_LOGGER_ENABLED', true),

    /*
     * When the clean-command is executed, all recording audits older than
     * the number of days specified here will be deleted.
     */
    'delete_records_older_than_days' => 365,

    /*
     * If no log name is passed to the audit() helper
     * we use this default log name.
     */
    'default_log_name' => 'default',

    /*
     * You can specify an auth driver here that gets user models.
     * If this is null we'll use the default Laravel auth driver.
     */
    'default_auth_driver' => null,

    /*
     * If set to true, the subject returns soft deleted models.
     */
    'subject_returns_soft_deleted_models' => false,

    /*
     * This model will be used to log audit. The only requirement is that
     * it should be or extend the \Sdon2\AuditLog\Models\AuditLog model.
     */
    'audit_log_model' => \Sdon2\AuditLog\Models\AuditLog::class,

    /*
     * If set to true, it will store ip address to the database
     */
    'track_ip' => true,
];

记录模型事件

此包的一个巧妙功能是它可以自动记录模型创建、更新和删除等事件。要使此功能正常工作,您只需让您的模型使用 Sdon2\AuditLog\Traits\LogsAudit - trait。

作为奖励,当在模型上设置 $logAttributes 属性时,包还会记录所有这些事件的更改属性。

以下是一个示例

use Illuminate\Database\Eloquent\Model;
use Sdon2\AuditLog\Traits\LogsAudit

class NewsItem extends Model
{
    use LogsAudit;

    protected $fillable = ['name', 'text'];
    
    protected static $logAttributes = ['name', 'text'];
}

让我们看看创建该模型实例时记录了什么。

$newsItem = NewsItem::create([
   'name' => 'original name',
   'text' => 'New Text'
]);

//creating the newsItem will cause an activity being logged
$auditLog = AuditLog::all()->last();

$auditLog->description; //returns 'created'
$auditLog->subject; //returns the instance of NewsItem that was created
$auditLog->changes; //returns ['attributes' => ['name' => 'original name', 'text' => 'Text']];

现在,让我们更新一些 $newsItem

$newsItem->name = 'updated name'
$newsItem->save();

//updating the newsItem will cause an activity being logged
$auditLog = AuditLog::all()->last();

$auditLog->description; //returns 'updated'
$auditLog->subject; //returns the instance of NewsItem that was created

调用 $auditLog->changes 将返回此数组

[
   'attributes' => [
        'name' => 'updated name',
        'text' => 'New text',
    ],
    'old' => [
        'name' => 'original name',
        'text' => 'Old text',
    ],
];

现在,调用删除会发生什么?

$newsItem->delete();

//deleting the newsItem will cause an activity being logged
$auditLog = AuditLog::all()->last();

$auditLog->description; //returns 'deleted'
$auditLog->changes; //returns ['attributes' => ['name' => 'updated name', 'text' => 'Text']];

自定义记录事件

默认情况下,包将记录 createdupdateddeleted 事件。您可以通过设置模型上的 $recordEvents 属性来修改此行为。

use Illuminate\Database\Eloquent\Model;
use Sdon2\AuditLog\Traits\CausesAudit;

class NewsItem extends Model
{
    use CausesAudit;

    //only the `deleted` event will get logged automatically
    protected static $recordEvents = ['deleted'];
}

自定义描述

默认情况下,包将在活动描述中记录 createdupdateddeleted。您可以通过覆盖 getDescriptionForEvent 函数来修改此文本。

use Illuminate\Database\Eloquent\Model;
use Sdon2\AuditLog\Traits\CausesAudit;

class NewsItem extends Model
{
    use CausesAudit;

    protected $fillable = ['name', 'text'];

    public function getDescriptionForEvent(string $eventName): string
    {
        return "This model has been {$eventName}";
    }

}

现在让我们看看发生了什么

$newsItem = NewsItem::create([
   'name' => 'original name',
   'text' => 'original Text'
]);

//creating the newsItem will cause an activity being logged
$auditLog = AuditLog::all()->last();

$auditLog->description; //returns 'This model has been created'

忽略某些属性的变化

如果您的模型包含不需要触发活动记录的属性变化,您可以使用 $ignoreChangedAttributes

use Illuminate\Database\Eloquent\Model;
use Sdon2\AuditLog\Traits\LogsAudit;

class NewsItem extends Model
{
    use LogsAudit;
    
    protected static $ignoreChangedAttributes = ['text'];

    protected $fillable = ['name', 'text'];
    
    protected static $logAttributes = ['name', 'text'];
}

更改 text 不会触发审计记录。

默认情况下,updated_at 属性不会被忽略,并将触发活动记录。您只需将 updated_at 属性添加到 $ignoreChangedAttributes 数组中即可覆盖此行为。

仅记录更改的属性

如果您不希望记录 $logAttributes 变量中的每个属性,但只想记录更新后实际更改的属性,则可以使用 $logOnlyDirty

use Illuminate\Database\Eloquent\Model;
use Sdon2\AuditLog\Traits\LogsAudit;

class NewsItem extends Model
{
    use LogsAudit;

    protected $fillable = ['name', 'text'];
    
    protected static $logAttributes = ['name', 'text'];
    
    protected static $logOnlyDirty = true;
}

仅更改 name 意味着只有活动中的 name 属性将被记录,而 text 将被忽略。

使用 CausesAudit trait

此包包含一个 CausesAudit trait,可以添加到任何用作触发者的模型。它提供了一个 auditLog 关系,返回由模型引起的所有活动。

如果将其包含在 User 模型中,您可以简单地像这样检索所有当前用户的操作

\Auth::user()->auditLog;