Yii2 实现数据库操作日志

11 篇文章 0 订阅
8 篇文章 0 订阅

1创建迁移文件

<?php

use yii\db\Schema;
use yii\db\Migration;

class m200817_080729_operation_log extends Migration
{

    public function init()
    {
        $this->db = 'db';
        parent::init();
    }

    public function safeUp()
    {
        $tableOptions = "COMMENT = '操作日志' CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB";

        $this->createTable(
            '{{%common_operation_log}}',
            [
                'id'=> $this->primaryKey(11),
                'method'=> $this->tinyInteger(1)->notNull()->defaultValue(0)->comment('0:get;1post'),
                'module'=> $this->string(50)->notNull()->defaultValue('')->comment('模块'),
                'controller'=> $this->string(50)->notNull()->defaultValue('')->comment('控制器'),
                'action'=> $this->string(50)->notNull()->defaultValue('')->comment('方法'),
                'ip'=> $this->string(16)->notNull()->defaultValue(''),
                'user_id'=> $this->integer(11)->defaultValue(0)->comment('根据提交模块不同对应人员不同'),
                'created_at'=> $this->integer(11)->notNull()->defaultValue(0)->comment('创建时间'),
                'description'=> $this->text()->null()->defaultValue(null)->comment('修改数据'),
                'table'=> $this->string(50)->notNull()->defaultValue('')->comment('操作表名称'),
                'type'=> $this->tinyInteger(1)->notNull()->defaultValue(0)->comment('类型0:INSERT;1:UPDATE;2:DELETE'),
                'source'=> $this->string(10)->null()->defaultValue('')->comment('设备来源'),
                'app_id'=> $this->string(10)->null()->defaultValue('')->comment('应用id'),
                'alter_id'=> $this->integer(11)->null()->defaultValue(0)->comment('修改相关数据的id')
            ],$tableOptions
        );
        $this->createIndex('user_id','{{%common_operation_log}}',['user_id'],false);
        $this->createIndex('app_id','{{%common_operation_log}}',['app_id'],false);
        $this->createIndex('module','{{%common_operation_log}}',['module'],false);
        $this->createIndex('controller','{{%common_operation_log}}',['controller'],false);
        $this->createIndex('action','{{%common_operation_log}}',['action'],false);

    }

    public function safeDown()
    {
        $this->dropIndex('user_id', '{{%common_operation_log}}');
        $this->dropIndex('app_id', '{{%common_operation_log}}');
        $this->dropIndex('module', '{{%common_operation_log}}');
        $this->dropIndex('controller', '{{%common_operation_log}}');
        $this->dropIndex('action', '{{%common_operation_log}}');
        $this->dropTable('{{%common_operation_log}}');
    }
}

2创建common\components\AdminLog.php文件

<?php


namespace common\components;


use common\models\base\OperationLog;
use Yii;
use yii\db\ActiveRecord;

class AdminLog
{
    public static function log($event): void
    {
        if ($event->sender instanceof OperationLog || !$event->sender->primaryKey()) {
            return;
        }
        $attributeLabels = (new $event->sender())->attributeLabels();
        $data['table'] = $event->sender->tableSchema->name;
        if ($event->name == ActiveRecord::EVENT_AFTER_INSERT) {
            $data['type'] = 0;
        } elseif ($event->name == ActiveRecord::EVENT_AFTER_UPDATE) {
            $data['type'] = 1;
        } else {
            $data['type'] = 2;
        }
        $data['app_id'] = Yii::$app->id;
        $data['method'] = Yii::$app->request->method;
        $data['module'] = Yii::$app->controller->module->id ?? '';
        $data['controller'] = Yii::$app->controller->id ?? '';
        $data['action'] = Yii::$app->controller->action->id ?? '';
        $data['ip'] = (string)ip2long(Yii::$app->request->userIP);
        $data['source'] = Yii::$app->request->headers->get('source');
        $desc = [];
        if (!empty($event->changedAttributes)) {
            foreach ($event->changedAttributes as $name => $value) {
                $newValue = $event->sender->getAttribute($name);
                if (isset($newValue) && $value != $newValue) {//当发生更改才会记录
                    $desc[] = ['name'=>$attributeLabels[$name],'old'=>$value ,'new'=>$newValue];
                }
            }
        }
        $data['description'] = json_encode($desc);
        $data['user_id'] = Yii::$app->user->identity->id ?? 0;
        $data['alter_id'] = is_array($event->sender->getPrimaryKey()) ? current(
            $event->sender->getPrimaryKey()
        ) : $event->sender->getPrimaryKey();
        $data['created_at'] = time();
        if ($desc) {
            Yii::$app->db->createCommand()->insert('saas_common_operation_log', $data)->execute();
        }
    }
}

3进行全局配置

    'bootstrap' => [
        static function(){
            Event::on(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_INSERT, ['common\components\AdminLog', 'log']);
            Event::on(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_UPDATE, ['common\components\AdminLog', 'log']);
            Event::on(BaseActiveRecord::className(), BaseActiveRecord::EVENT_AFTER_DELETE, ['common\components\AdminLog', 'log']);
        },
    ],

4进行测试并查看数据库记录

具体数据库

5业务使用可以做某个功能的操作日志

此处是订单的操作日志

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值