LogService.php 2.1 KB

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