配置main.php
##在backend/config/main.php添加
#和components同级
'on beforeRequest' => function($event) {
\yii\base\Event::on(\yii\db\BaseActiveRecord::className(),
\yii\db\BaseActiveRecord::EVENT_AFTER_UPDATE, ['common\models\TbLog', 'write']);##日志model和写日志静态方法
},
配置日志model和写入方法
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
class TbLog extends \common\models\BaseModel
{
public static function tableName()
{
return "{{%tb_log}}";
}
public static function write($event)
{
// 排除日志表自身,没有主键的表不记录(没想到怎么记录。。每个表尽量都有主键吧,不一定非是自增id)
if($event->sender instanceof \common\models\TbLog || !$event->sender->primaryKey()) {
return;
}
$log_format = "修改 {%s} 由 {%s} 修改为 {%s},";
$cookie = \Yii::$app->request->cookies;
$admin_id = $cookie->getValue('uid', 0);
$admin_name = $cookie->getValue('name', '');
// 显示详情有待优化,不过基本功能完整齐全
if ($event->name == ActiveRecord::EVENT_AFTER_INSERT) {
$description = "%s新增了表%s %s:%s的%s";
} elseif($event->name == ActiveRecord::EVENT_AFTER_UPDATE) {
$description = "%s修改了表%s %s:%s的%s";
} else {
$description = "%s删除了表%s %s:%s%s";
}
if (!empty($event->changedAttributes)) {
$desc = '';
foreach($event->changedAttributes as $name => $value) {
if ($value == $event->sender->getAttribute($name)) {
continue;
}
$desc .= sprintf($log_format, $name,$value, $event->sender->getAttribute($name));
}
$desc = substr($desc, 0, -1);
} else {
$desc = '';
}
$userName = $admin_name;
$tableName = $event->sender->tableSchema->name;
$description = sprintf($description, $userName, $tableName, $event->sender->primaryKey()[0], $event->sender->getPrimaryKey(), $desc);
$log = new TbLog();
$log->admin_id = $admin_id;
$log->admin_name = $admin_name;
$log->info = $description;
$log->create_time = time();
$log->save();
}
}
可以了,只需要两步,操作时就能自动增加没个对数据库的操作日志,自行测试日志是否增加吧