You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.4 KiB

  1. <?php
  2. namespace App\Commons;
  3. use Hyperf\Guzzle\ClientFactory;
  4. class Log
  5. {
  6. /**
  7. * @var \Hyperf\Guzzle\ClientFactory
  8. */
  9. private $clientFactory;
  10. public function __construct(ClientFactory $clientFactory)
  11. {
  12. $this->clientFactory = $clientFactory;
  13. }
  14. public function getClient()
  15. {
  16. // $options 等同于 GuzzleHttp\Client 构造函数的 $config 参数
  17. $options = [
  18. 'timeout' => 2.0,
  19. ];
  20. // $client 为协程化的 GuzzleHttp\Client 对象
  21. $client = $this->clientFactory->create($options);
  22. return $client;
  23. }
  24. public function event($labels=null,$datas){
  25. co(function () use ($labels,$datas){
  26. $client = $this->getClient();
  27. $kv = [];
  28. foreach ($datas as $key => $value) {
  29. $kv[] = $key."=".$value;
  30. }
  31. $pushLabels = [];
  32. $event_name = 'event_'.env('APP_ENV');
  33. if(!empty($labels)) $pushLabels[$event_name] = $labels;
  34. /*
  35. * data format:
  36. curl -v -H "Content-Type: application/json" -XPOST -s "http://39.96.12.39:3100/loki/api/v1/push" --data-raw \
  37. '{"streams": [{ "stream": { "foo": "bar2" }, "values": [ [ "1596274538882028800", "fizzbuzz" ] ] }]}'
  38. */
  39. $ts = $this->getMsecTime() . '000000';
  40. $datas = implode("&",$kv);
  41. $values = [[$ts,$datas]];
  42. $app_name = env('APP_NAME').'_'.env('APP_ENV');
  43. $pushLabels['app']= $app_name;
  44. $pushDatas = [
  45. 'streams'=>[
  46. [
  47. 'stream'=>$pushLabels,
  48. 'values'=>$values,
  49. ]
  50. ]
  51. ];
  52. $client->post(
  53. 'http://39.96.12.39:3100/loki/api/v1/push',
  54. [
  55. 'headers'=>[
  56. 'Content-Type'=>'application/json'
  57. ],
  58. 'body' => json_encode($pushDatas)
  59. ]
  60. );
  61. //var_dump(json_encode($pushDatas) );
  62. });
  63. }
  64. public function push($datas){
  65. $this->event(null,$datas);
  66. }
  67. public function getMsecTime()
  68. {
  69. list($msec, $sec) = explode(' ', microtime());
  70. $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
  71. return $msectime;
  72. }
  73. }