LogService.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. }
  28. $date = date('Y-m-d H:i:s');
  29. $log = new Log([
  30. 'operation' => $method,
  31. 'type' => $type,
  32. 'description' => $description,
  33. 'id_user' => $id_user,
  34. 'ip' => Request::ip(),
  35. 'created_at' => $date,
  36. 'updated_at' => $date
  37. ]);
  38. Redis::LPUSH('LOGS', $log);
  39. }
  40. public static function syncRedisLogs()
  41. {
  42. try {
  43. Redis::LLEN('LOGS');
  44. } catch (Exception $e) {
  45. session()->flash('danger', 'Redis服务异常无法正常同步,最新日志已直接保存到数据库中,但已缓存的日志无法同步,请检查Redis是否正常,然后再尝试同步');
  46. return;
  47. }
  48. $data = [];
  49. $length = 0;
  50. while (Redis::LLEN('LOGS') > 0) {
  51. $log = Redis::LPOP('LOGS');
  52. $arr = json_decode($log);
  53. if ($length + strlen($arr->description) > 1024 * 512) {
  54. Log::query()->insert($data);
  55. $length = 0;
  56. $data = [];
  57. }
  58. $length = $length + strlen($arr->description);
  59. $data[] = [
  60. 'operation' => $arr->operation,
  61. 'id_user' => $arr->id_user,
  62. 'ip' => $arr->ip,
  63. 'type' => $arr->type,
  64. 'description' => $arr->description,
  65. 'created_at' => $arr->created_at,
  66. 'updated_at' => $arr->updated_at,
  67. ];
  68. }
  69. if ($data) {
  70. Log::query()->insert($data);
  71. }
  72. }
  73. }