HttpEndListener.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\listener\http;
  12. use think\facade\Log;
  13. use think\Response;
  14. /**
  15. * 请求结束事件
  16. * Class Create
  17. * @package app\listener\http
  18. */
  19. class HttpEndListener
  20. {
  21. public function handle(Response $response):void
  22. {
  23. //业务成功和失败分开存储
  24. $status = $response->getData()["status"] ?? 0;
  25. if ($status == 200) {
  26. //业务成功日志开关
  27. if (!config("log.success_log")) return;
  28. $type = "success";
  29. } else {
  30. //业务失败日志开关
  31. if (!config("log.fail_log")) return;
  32. $type = "fail";
  33. }
  34. //当前用户身份标识
  35. if (!empty(request()->uid())) {
  36. $uid = request()->uid();
  37. } elseif (!empty(request()->adminId())) {
  38. $uid = request()->adminId();
  39. } elseif (!empty(request()->kefuId())) {
  40. $uid = request()->kefuId();
  41. } else {
  42. $uid = 0;
  43. }
  44. //日志内容
  45. $log = [
  46. $uid, //用户ID
  47. request()->ip(), //客户ip
  48. ceil(msectime() - (request()->time(true) * 1000)), //耗时(毫秒)
  49. request()->rule()->getMethod(), //请求类型
  50. str_replace("/", "", request()->rootUrl()), //应用
  51. request()->baseUrl(), //路由
  52. json_encode(request()->param(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), //请求参数
  53. json_encode($response->getData(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), //响应数据
  54. ];
  55. Log::write(implode("|", $log), $type);
  56. }
  57. }