LogService.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Services;
  3. use App\Log;
  4. use Illuminate\Support\Facades\Redis;
  5. use Illuminate\Support\Facades\Request;
  6. class LogService
  7. {
  8. static public function log($method,$type,$description,$id_user=null){
  9. if(!$id_user){
  10. $id_user = '';
  11. $user=auth()->user();
  12. if($user) $id_user = $user['id'];
  13. }
  14. $date = date('Y-m-d H:i:s');
  15. $log = new Log([
  16. 'operation'=>$method,
  17. 'type'=>$type,
  18. 'description'=>$description,
  19. 'id_user'=>$id_user,
  20. 'ip'=>Request::ip(),
  21. 'created_at' => $date,
  22. 'updated_at' => $date
  23. ]);
  24. Redis::LPUSH('LOGS', $log);
  25. }
  26. public static function syncRedisLogs()
  27. {
  28. $data = [];
  29. $length = 0;
  30. while (Redis::LLEN('LOGS') > 0) {
  31. $log = Redis::LPOP('LOGS');
  32. $arr = json_decode($log);
  33. if ($length + strlen($arr->description) > 1024 * 512) {
  34. Log::query()->insert($data);
  35. $length = 0;
  36. $data = [];
  37. }
  38. $length = $length + strlen($arr->description);
  39. $data[] = [
  40. 'operation' => $arr->operation,
  41. 'id_user' => $arr->id_user,
  42. 'ip' => $arr->ip,
  43. 'type' => $arr->type,
  44. 'description' => $arr->description,
  45. 'created_at' => $arr->created_at,
  46. 'updated_at' => $arr->updated_at,
  47. ];
  48. }
  49. if ($data) {
  50. Log::query()->insert($data);
  51. }
  52. }
  53. }