LogService.php 2.2 KB

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