ASCII码 ASCII码

Laravel实现将数据库操作记入日志

发布于:2022-04-12 10:22:17  栏目:技术文档

日志数据表迁移文件

  1. <?php
  2. use Illuminate\Database\Migrations\Migration;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Support\Facades\Schema;
  5. class CreateLogsTable extends Migration
  6. {
  7. /**
  8. * Run the migrations.
  9. *
  10. * @return void
  11. */
  12. public function up()
  13. {
  14. Schema::create('logs', function (Blueprint $table) {
  15. $table->id();
  16. $table->string('username',50)->comment('用户名');
  17. $table->string('query')->comment('SQL语句');
  18. $table->string('para')->comment('参数');
  19. $table->timestamps();
  20. });
  21. }
  22. /**
  23. * Reverse the migrations.
  24. *
  25. * @return void
  26. */
  27. public function down()
  28. {
  29. Schema::dropIfExists('logs');
  30. }
  31. }

Log 模型文件

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Log extends Model
  6. {
  7. use HasFactory;
  8. protected $guarded=[];
  9. }

存入日志记录表

  1. //启用数据操作日志
  2. DB::enableQueryLog();
  3. Book::create(['name'=>'Laravel框架']);
  4. $log['username']="admin";
  5. //(DB::getQueryLog()获取操作日志,是一个二维数组
  6. foreach(DB::getQueryLog() as $operation){
  7. $log['query']=$operation['query'];
  8. $log['para']="";
  9. foreach ($operation['bindings'] as $para){
  10. $log['para'].=$para.",";
  11. }
  12. }
  13. Log::create($log);

以上代码,以使用模型进行数据的添加为例进行说明的,模型的其他操作同样可以写入日志,使用构造查询器也可以将对数据的操作存入日志

相关推荐
阅读 +