aliirfaan/laravel-simple-audit-log

此包创建一个数据库表来保存审计日志,并公开事件以记录用户操作。

8.0.0 2024-05-13 16:55 UTC

This package is auto-updated.

Last update: 2024-09-13 17:45:43 UTC


README

许多系统需要记录用户操作以进行审计。此包创建一个包含合理字段的数据库表以记录操作。

特性

  • 审计日志表结构
  • 事件驱动
  • 可配置连接(如果使用不同的数据库记录日志)
  • 可配置模型

表字段

这只是一个用于说明字段的示例。表将通过Laravel迁移文件创建。

Schema::connection(config('simple-audit-log.audit_log_db_connection'))->create('lsal_audit_logs', function (Blueprint $table) {
    $table->dateTime('al_date_time_local', $precision = 0)->index('al_date_time_local_index')->comment('Timestamp in local timezone.');
    $table->id();
    $table->dateTime('al_date_time_utc', $precision = 0)->nullable()->index('al_date_time_utc_index');
    $table->string('al_actor_id')->nullable()->index('al_actor_id_index')->comment('User id in application. Can be null in cases where an action is performed programmatically.');
    $table->string('al_actor_type', 255)->nullable()->index('al_actor_type_index')->comment('Actor type in application. Useful if you are logging multiple types of users. Example: admin, user, guest');
    $table->string('al_actor_global_uid')->nullable()->index('al_actor_global_uid_index')->comment('User id if using a single sign on facility.');
    $table->string('al_actor_username', 255)->nullable()->index('al_actor_username_index')->comment('Username in application.');
    $table->string('al_actor_group', 255)->nullable()->index('al_actor_group_index')->comment('User role/group in application.');
    $table->string('al_device_id', 255)->nullable()->index('al_device_id_index')->comment('Device identifier.');
    $table->string('al_target_name', 255)->nullable()->index('al_target_name_index')->comment('The object or underlying resource that is being accessed. Example: user.');
    $table->string('al_target_id')->nullable()->index('al_target_id_index')->comment('The ID of the resource that is being accessed.');
    $table->string('al_action_type', 255)->nullable()->index('al_action_type_index')->comment('CRUD: Read, write, update, delete');
    $table->string('al_event_name', 255)->index('al_event_name_index')->comment('Common name for the event that can be used to filter down to similar events. Example: user.login.success, user.login.failure, user.logout');
    $table->string('al_correlation_id', 255)->nullable()->index('al_correlation_id_index')->comment('Correlation id for easy traceability and joining with other tables.');
    $table->string('al_parent_correlation_id', 255)->nullable()->index('al_parent_correlation_id_index')->comment('Correlation id for easy traceability and joining with other tables.');
    $table->tinyInteger('al_is_success')->nullable()->default(0)->index('al_is_success_index');
    $table->text('al_meta')->nullable();
    $table->text('al_message')->nullable();
    $table->text('al_previous_value')->nullable();
    $table->text('al_new_value')->nullable();
    $table->text('al_request')->nullable()->comment('Request information.');
    $table->text('al_response')->nullable()->comment('Response information.');
    $table->ipAddress('al_ip_addr')->nullable()->index('al_ip_addr_index');
    $table->string('al_server', 255)->nullable()->index('al_server_index')->comment('Server ids or names, server location. Example: uat, production, testing, 192.168.2.10');
    $table->string('al_version', 255)->nullable()->index('al_version_index')->comment('Version of the code/release that is sending the events.');
    $table->string('al_log_level', 10)->nullable()->index('al_log_level_index')->comment('Log level.');
    $table->string('al_code', 50)->nullable()->index('al_code_index')->comment('Error code.');
    $table->timestamps();
});

事件

您可以将这些事件分发以记录日志。如果需要额外的处理,您也可以监听这些事件。

  • AuditLogged

要求

安装

您可以使用composer在现有的Laravel项目中安装此包

 $ composer require aliirfaan/laravel-simple-audit-log

通过编辑 config/app.php 文件并添加到提供者数组中,来注册ServiceProvider

  aliirfaan\LaravelSimpleAuditLog\SimpleAuditLogProvider::class,

注意:对于Laravel <5.1版本,使用以下内容

 'aliirfaan\LaravelSimpleAuditLog\SimpleAuditLogProvider',

使用以下命令发布文件

 $ php artisan vendor:publish --provider="aliirfaan\LaravelSimpleAuditLog\SimpleAuditLogProvider"

或者只使用 php artisan vendor:publish 并从输出列表中选择 aliirfaan\LaravelSimpleAuditLog\SimpleAuditLogProvider

应用迁移

 $ php artisan migrate

配置

此包在应用程序的 config 文件夹中发布一个 simple-audit-log.php 文件,其中包含此包的设置。大多数变量绑定到环境变量,但您可以直接编辑此文件或将配置键添加到 .env 文件中。

audit_log_db_connection | String
要使用的数据库连接。默认为环境变量 'DB_CONNECTION'。

'audit_log_db_connection' => env('AUDIT_LOG_DB_CONNECTION', env('DB_CONNECTION'))

audit_log_model | String 您要使用的模型。该模型必须实现 aliirfaan\LaravelSimpleAuditLog\Contracts\SimpleAuditLog

'audit_log_model' => aliirfaan\LaravelSimpleAuditLog\Models\SimpleAuditLog::class,

should_prune | Boolean 是否要修剪记录

'should_prune' => env('AUDIT_LOG_SHOULD_PRUNE', false),

prune_month | Numeric 删除超过prune_months的记录

'prune_month' => env('AUDIT_LOG_PRUNE_MONTH', 3)

用法

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use aliirfaan\LaravelSimpleAuditLog\Events\AuditLogged; // event you want to dispatch

class TestController extends Controller
{
    public function test(Request $request)
    {
        try {

            // log access after operation
            $eventData = [
                'al_date_time_local'=> date('Y-m-d H:i:s'),
                'al_date_time_utc'=> date('Y-m-d H:i:s'),
                'al_actor_id'=> 5,
                'al_event_name'=> 'user.login.success',
                'al_ip_addr'=> $request->ip()
            ];

            // dispatch event
            AuditLogged::dispatch($eventData);

        } catch (\Exception $e) {
            report($e);
        }
    }
}

自定义模型

如果您对我们的审计日志有额外的要求,您可以使用迁移添加列,并使用自定义模型使用新列。

将您的自定义模型添加到配置文件中。

<?php

namespace App\Models\AuditLog;

use Illuminate\Database\Eloquent\Model;
use aliirfaan\LaravelSimpleAuditLog\Contracts\SimpleAuditLog as SimpleAuditLogContract;
use aliirfaan\LaravelSimpleAuditLog\Models\SimpleAuditLog;

// custom class that extends base model and implements contract
class AuditLog extends SimpleAuditLog implements SimpleAuditLogContract
{
    public function __construct(array $attributes = [])
    {
        // add your additional columns to the fillable property
        $this->mergeFillable(['al_custom_field_1']);
        
        parent::__construct($attributes);
    }
}

指定自定义模型到配置文件

'audit_log_model' => App\Models\AuditLog\AuditLog::class,

许可证

MIT许可证(MIT)

版权所有 (c) 2020

以下是对任何获得此软件及其相关文档副本(“软件”)的人的授权,免费使用软件,不受任何限制,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件副本的权利,以及允许向软件提供者提供软件的人进行此类操作,前提是满足以下条件

上述版权声明和本许可声明应包含在软件的副本或主要部分中。

软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、适用于特定目的和无侵犯性的保证。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任承担责任,无论此类索赔、损害或其他责任是基于合同、侵权或其他方式,是否因软件或其使用或其他方式而产生。