LogService.php 2.4 KB

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