LogService.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. if ($length + strlen($description) > 1024 * 512) {
  60. Log::query()->insert($data);
  61. $length = 0;
  62. $data = [];
  63. }
  64. $length = $length + strlen($description);
  65. $data[] = [
  66. 'class' => $arr->class,
  67. 'id_user' => $arr->id_user,
  68. 'ip' => $arr->ip,
  69. 'method' => $arr->method,
  70. 'description' => $description,
  71. 'created_at' => $arr->created_at,
  72. 'updated_at' => $arr->updated_at,
  73. ];
  74. }
  75. if ($data) {
  76. Log::query()->insert($data);
  77. }
  78. }
  79. }