LogService.php 2.1 KB

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