stackdriver_util.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. require('../vendor/autoload.php');
  3. use Google\Cloud\ErrorReporting\V1beta1\ReportErrorsServiceClient;
  4. use Google\Cloud\ErrorReporting\V1beta1\ErrorContext;
  5. use Google\Cloud\ErrorReporting\V1beta1\ReportedErrorEvent;
  6. use Google\Cloud\ErrorReporting\V1beta1\SourceLocation;
  7. class StackdriverUtil{
  8. function __construct($api){
  9. $this->api = $api;
  10. $this->metrics = [];
  11. $this->success = FALSE;
  12. $this->err_client = new ReportErrorsServiceClient();
  13. }
  14. function addMetric($key, $value){
  15. $this->matrics[$key] = $value;
  16. }
  17. function addMetrics($metrics){
  18. $this->metrics = array_merge($metrics, $this->metrics);
  19. }
  20. function setSuccess($result){
  21. $this->success = $result;
  22. }
  23. function outputMetrics(){
  24. if ($this->success){
  25. echo $this->api.'_success 1'."\n";
  26. }
  27. else{
  28. echo $this->api.'_success 0'."\n";
  29. }
  30. foreach ($this->metrics as $key => $value) {
  31. echo $key.' '.$value."\n";
  32. }
  33. }
  34. function reportError($err){
  35. error_log($err);
  36. $projectId = '434076015357';
  37. $project_name = $this->err_client->projectName($projectId);
  38. $location = (new SourceLocation())
  39. ->setFunctionName($this->api);
  40. $context = (new ErrorContext())
  41. ->setReportLocation($location);
  42. $error_event = new ReportedErrorEvent();
  43. $error_event->setMessage('PHPProbeFailure: fails on '.$this->api.' API. Details: '.(string)$err."\n");
  44. $error_event->setContext($context);
  45. $this->err_client->reportErrorEvent($project_name, $error_event);
  46. }
  47. }