LogService.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. protected $modelClass = Log::class;
  11. static public function log($class, $method, $description, $id_user = null, $type = 'log')
  12. {
  13. $passingMethods = config('logging.passing_methods');
  14. foreach ($passingMethods as $passingMethod) {
  15. if ($passingMethod == $method) return;
  16. }
  17. if (!$id_user) {
  18. $id_user = '';
  19. $user = auth()->user();
  20. if ($user) $id_user = $user['id'];
  21. }
  22. $log = new Log([
  23. 'class' => $class,
  24. 'method' => $method,
  25. 'description' => $description,
  26. 'id_user' => $id_user,
  27. 'ip' => request()->ip(),
  28. 'type' => $type,
  29. ]);
  30. try {
  31. Redis::LLEN('LOGS');
  32. } catch (Exception $e) {
  33. //redis出现异常直接保存到数据库中
  34. $log->save();
  35. return;
  36. }
  37. $date = date('Y-m-d H:i:s');
  38. $log['created_at'] = $date;
  39. $log['updated_at'] = $date;
  40. Redis::LPUSH('LOGS', $log);
  41. }
  42. public static function syncRedisLogs()
  43. {
  44. try {
  45. Redis::LLEN('LOGS');
  46. } catch (Exception $e) {
  47. session()->flash('danger', 'Redis服务异常无法正常同步,最新日志已直接保存到数据库中,但已缓存的日志无法同步,请检查Redis是否正常,然后再尝试同步');
  48. return;
  49. }
  50. $data = [];
  51. $length = 0;
  52. while (Redis::LLEN('LOGS') > 0) {
  53. $log = Redis::LPOP('LOGS');
  54. $arr = json_decode($log);
  55. if (empty($arr)) {
  56. return;
  57. }
  58. $description = (is_string($arr->description) ? $arr->description : json_encode($arr->description)) ?? '';
  59. //当前日志超长,跳过该条,不插入
  60. if (strlen($description)> 1024 * 512) {
  61. continue;
  62. }
  63. if ($length + strlen($description) > 1024 * 512) {
  64. Log::query()->insert($data);
  65. $length = 0;
  66. $data = [];
  67. }
  68. $length = $length + strlen($description);
  69. $data[] = [
  70. 'class' => $arr->class,
  71. 'id_user' => $arr->id_user,
  72. 'ip' => $arr->ip,
  73. 'method' => $arr->method,
  74. 'description' => $description,
  75. 'created_at' => $arr->created_at,
  76. 'updated_at' => $arr->updated_at,
  77. ];
  78. }
  79. if ($data) {
  80. Log::query()->insert($data);
  81. }
  82. }
  83. }