LogService.php 2.5 KB

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