LogService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Services;
  3. use App\Log;
  4. use Exception;
  5. use Illuminate\Support\Facades\Redis;
  6. use Illuminate\Support\Facades\Request;
  7. class LogService
  8. {
  9. static public function log($method, $type, $description, $id_user = null)
  10. {
  11. if (!$id_user) {
  12. $id_user = '';
  13. $user = auth()->user();
  14. if ($user) $id_user = $user['id'];
  15. }
  16. try {
  17. Redis::LLEN('LOGS');
  18. } catch (Exception $e) {
  19. //redis出现异常直接保存到数据库中
  20. (new Log([
  21. 'operation' => $method,
  22. 'type' => $type,
  23. 'description' => $description,
  24. 'id_user' => $id_user,
  25. 'ip' => Request::ip(),
  26. ]))->save();
  27. return;
  28. }
  29. $date = date('Y-m-d H:i:s');
  30. $log = new Log([
  31. 'operation' => $method,
  32. 'type' => $type,
  33. 'description' => $description,
  34. 'id_user' => $id_user,
  35. 'ip' => Request::ip(),
  36. 'created_at' => $date,
  37. 'updated_at' => $date
  38. ]);
  39. Redis::LPUSH('LOGS', $log);
  40. }
  41. public static function syncRedisLogs()
  42. {
  43. try {
  44. Redis::LLEN('LOGS');
  45. } catch (Exception $e) {
  46. session()->flash('danger', 'Redis服务异常无法正常同步,最新日志已直接保存到数据库中,但已缓存的日志无法同步,请检查Redis是否正常,然后再尝试同步');
  47. return;
  48. }
  49. $data = [];
  50. $length = 0;
  51. while (Redis::LLEN('LOGS') > 0) {
  52. $log = Redis::LPOP('LOGS');
  53. $arr = json_decode($log);
  54. if ($length + strlen($arr->description) > 1024 * 512) {
  55. Log::query()->insert($data);
  56. $length = 0;
  57. $data = [];
  58. }
  59. $length = $length + strlen($arr->description);
  60. $data[] = [
  61. 'operation' => $arr->operation,
  62. 'id_user' => $arr->id_user,
  63. 'ip' => $arr->ip,
  64. 'type' => $arr->type,
  65. 'description' => $arr->description,
  66. 'created_at' => $arr->created_at,
  67. 'updated_at' => $arr->updated_at,
  68. ];
  69. }
  70. if ($data) {
  71. Log::query()->insert($data);
  72. }
  73. }
  74. }