LogService.php 2.2 KB

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