Save analytics

@param string $metric
@param array $tags
@param int $value
@param string $date
@param string $rp
@throws AnalyticsException
321784
public function save($metric, $tags = array(), $value = 1, $date = null, $rp = null) {
        try {
            return $this->mapper->save($metric, $tags, $value, $date, $rp);
        } catch (Exception $e) {
            throw new AnalyticsException("Analytics client save exception", 0, $e);
        }    
    }
964203
public void registerAny(Metric2Set metrics) {
		for (Map.Entry<MetricName, Metric> entry : metrics.getMetrics().entrySet()) {
			registerNewMetrics(entry.getKey(), entry.getValue());
		}
	}
402417
public function set($metric, $uniqueValue, array $tags = array(), $sampleRate = AbstractMetric::DEFAULT_SAMPLE_RATE)
    {
        try {
            $this->sendMetric($this->metricFactory->set($metric, $uniqueValue, $tags, $sampleRate));
        } catch (\Exception $exception) {
            $this->logException($exception);
        }

        return $this;
    }
917513
protected function processMetaTags(array &$tags)
    {
        // Call hook
        GeneralUtility::callHookAndSignal(__CLASS__, 'metatagOutput', $this, $tags);

        // Add marker
        $markerList = array(
            '%YEAR%' => date('Y'),
        );

        $keyList = array(
            'meta.title',
            'meta.description',
            'meta.description.dc',
            'meta.keywords',
            'meta.keywords.dc',
            'meta.copyright',
            'meta.copyright.dc',
            'meta.publisher.dc',
        );

        foreach ($keyList as $key) {
            if (!empty($tags[$key]['attributes'])) {
                foreach ($markerList as $marker => $value) {
                    foreach ($tags[$key]['attributes'] as &$metaTagAttribute) {
                        // only replace markers if they are present
                        if (strpos($metaTagAttribute, $marker) !== false) {
                            $metaTagAttribute = str_replace($marker, $value, $metaTagAttribute);
                        }
                    }
                    unset($metaTagAttribute);
                }
            }
        }
    }
792090
public function applyMetrics($qb, &$metrics, $associationMappings, $classMetadata, $joins)
    {
        foreach ($metrics as $metricItemKey => $metricItem) {
            $metric = $metricItem['field'];
            $metric_name = str_replace('.', '___', $metric) . '___' . $metricItem['aggregation'];
            $metrics[$metricItemKey]['code_name'] = $metric_name;

            if (false !== mb_strpos($metric, '.')) {
                $metric_parts = explode('.', $metric);
                $metrics[$metricItemKey]['label_name'] = $this->camelCaseToUnderscore($metric_parts[0]);

                /** @var array $associationMapping */
                $associationMapping = $associationMappings[$metric_parts[0]];

                $associationTargetClass = $classMetadata->getAssociationTargetClass($metric_parts[0]);

                $on = '';

                /** @var array $sourceToTargetKeyColumns */
                $sourceToTargetKeyColumns = $associationMapping['sourceToTargetKeyColumns'];

                foreach ($sourceToTargetKeyColumns as $source => $target) {
                    $on = 'entity.' . $source . ' = ' . $metric_parts[0] . '_join';
                }

                if (!\in_array($associationTargetClass, $joins)) {
                    $joins[] = $associationTargetClass;
                    $qb->leftJoin($associationTargetClass, $metric_parts[0] . '_join', 'WITH', $on);
                }

                $qb->addSelect($metricItem['aggregation'] . '(' . $metric . ') as ' . $metric_name);
            } else {
                $metrics[$metricItemKey]['label_name'] = $this->camelCaseToUnderscore($metric);

                $qb->addSelect($metricItem['aggregation'] . '(' . 'entity.' . $metric . ') as ' . $metric_name);
            }
        }

        return $qb;
    }
1253314
private void postMetricMetadata(String metricName, DatadogMetricMetadata metadata) {
        // already posted the metadata for this metric
        if (verifiedMetadata.contains(metricName))
            return;

        try {
            httpClient
                    .put(config.uri() + "/api/v1/metrics/" + URLEncoder.encode(metricName, "UTF-8")
                            + "?api_key=" + config.apiKey() + "&application_key=" + config.applicationKey())
                    .withJsonContent(metadata.editMetadataBody())
                    .send()
                    .onSuccess(response -> verifiedMetadata.add(metricName))
                    .onError(response -> {
                        if (logger.isErrorEnabled()) {
                            String msg = response.body();

                            // Ignore when the response content contains "metric_name not found".
                            // Metrics that are newly created in Datadog are not immediately available
                            // for metadata modification. We will keep trying this request on subsequent publishes,
                            // where it will eventually succeed.
                            if (!msg.contains("metric_name not found")) {
                                logger.error("failed to send metric metadata to datadog: {}", msg);
                            }
                        }
                    });
        } catch (Throwable e) {
            logger.warn("failed to send metric metadata to datadog", e);
        }
    }
858381
private function getDataDateRange($viewId,$dateStart,$dateEnd,$metric, $dimensions = null) {
		if(!$this->isEnabled()) return null;

		// Create the DateRange object
		$dateRange = new Google_Service_AnalyticsReporting_DateRange();
		$dateRange->setStartDate($dateStart);
		$dateRange->setEndDate($dateEnd);
		// Create the Metrics object
		$sessions = new Google_Service_AnalyticsReporting_Metric();
		$sessions->setExpression("ga:$metric");
		$sessions->setAlias("$metric");
		if (isset($dimensions) && is_array($dimensions)) {
			$this->reportingDimensions = [];
			foreach ($dimensions as $dimension) {
				// Create the segment dimension.
				$reportingDimensions = new Google_Service_AnalyticsReporting_Dimension();
				$reportingDimensions->setName("ga:$dimension");
				$this->reportingDimensions[] = $reportingDimensions;
			}
		}
		// Create the ReportRequest object
		$request = new Google_Service_AnalyticsReporting_ReportRequest();
		$request->setViewId($viewId);
		$request->setDateRanges($dateRange);
		// add dimensions
		if (isset($this->reportingDimensions) && is_array($this->reportingDimensions))
			$request->setDimensions($this->reportingDimensions);
		$request->setMetrics([$sessions]);
		$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
		$body->setReportRequests([$request]);
		$report = $this->analytics->reports->batchGet($body);
		$result = $report->getReports()[0]
			->getData()
			->getTotals()[0]
			->getValues()[0]
		;
		return $result;
	}
52107
function(eventTags, logger) {
    if (eventTags && eventTags.hasOwnProperty(REVENUE_EVENT_METRIC_NAME)) {
      var rawValue = eventTags[REVENUE_EVENT_METRIC_NAME];
      var parsedRevenueValue = parseInt(rawValue, 10);
      if (isNaN(parsedRevenueValue)) {
        logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.FAILED_TO_PARSE_REVENUE, MODULE_NAME, rawValue));
        return null;
      }
      logger.log(LOG_LEVEL.INFO, sprintf(LOG_MESSAGES.PARSED_REVENUE_VALUE, MODULE_NAME, parsedRevenueValue));
      return parsedRevenueValue;
    }
    return null;
  }
1046322
public static void log(Marker marker, PerformanceMetrics metrics) {
    if (log.isDebugEnabled()) {
      log.debug(marker, getEndMetrics(metrics));
    }
  }
321344
static void checkMetricAndTags(final String metric,
      final Map<String, String> tags) {
    if (tags.size() <= 0) {
      throw new IllegalArgumentException("Need at least one tag (metric="
          + metric + ", tags=" + tags + ')');
    } else if (tags.size() > Const.MAX_NUM_TAGS()) {
      throw new IllegalArgumentException("Too many tags: " + tags.size()
          + " maximum allowed: " + Const.MAX_NUM_TAGS() + ", tags: " + tags);
    }

    Tags.validateString("metric name", metric);
    for (final Map.Entry<String, String> tag : tags.entrySet()) {
      Tags.validateString("tag name with value [" + tag.getValue() + "]", 
          tag.getKey());
      Tags.validateString("tag value with key [" + tag.getKey() + "]", 
          tag.getValue());
    }
  }
771165
public function getRpPoints($rp, $metric, $tags, $granularity, $startDt = null, $endDt = null, $timezone = 'utc') {
        
        if (null == $rp || null == $metric) {
            return [];
        }
        
        $where = [];
        
        $query = $this->db->getQueryBuilder()
                ->retentionPolicy($rp)
                ->sum('value')
                ->from($metric);

        if (isset($endDt)) {
            $where[] = "time <= '" . $endDt . "'";
        }
        
        if (isset($startDt)) {
            $where[] = "time >= '" . $startDt . "'";
        }
        
        foreach ($tags as $key => $val) {
            $where[] = "$key = '" . $val . "'";
        }

        $query->where($where);
        
        $groupBy = "time(1d) tz('" . $timezone . "')";
        if ($granularity == self::GRANULARITY_HOURLY) {
            //timeoffset doesn't work hourly
            $groupBy = "time(1h) tz('" . $timezone . "')";
        } else if ($granularity == self::GRANULARITY_DAILY) {
            $groupBy = "time(1d) tz('" . $timezone . "')";
        } else if ($granularity == self::GRANULARITY_WEEKLY) {
            $groupBy = "time(1w) tz('" . $timezone . "')";
        }
        $query->groupBy($groupBy);

        return $query->getResultSet()->getPoints();
    }
1191083
public function performQuery(Period $period, string $metrics, array $others = [])
    {
        return $this->client->performQuery(
            $this->viewId,
            $period->startDate,
            $period->endDate,
            $metrics,
            $others
        );
    }
359355
public function start($metric, array $tags = array(), $sampleRate = AbstractMetric::DEFAULT_SAMPLE_RATE)
    {
        try {
            $this->timers[$metric] = $this->metricFactory->timer($metric, null, $tags, $sampleRate);
            $this->timers[$metric]->start();
        } catch (\Exception $exception) {
            $this->logException($exception);
        }

        return $this;
    }
57580
public function getPoints($metric, $tags, $granularity, $endDt, $timezone = 'utc') {
        if ( null == $metric ) {
            return [];
        }
        
        $where = [];

        $now = $this->normalizeUTC(date("Y-m-d H:i:s"));
        
        $min = intval(date('i'));
        $minutes = $min > 45 ? 45 : ( $min > 30 ? 30 : ( $min > 15 ? 15 : '00') );       
        $lastHourDt = date("Y-m-d") . "T" . date('H') . ":$minutes:00Z";
        
        if (strtotime($endDt) < strtotime($lastHourDt)) {
           return [];
        }
        
        $where[] = "time >= '" . $lastHourDt . "' AND time <= '" . $now  . "'";
        
        foreach ($tags as $key => $val) {
            $where[] = "$key = '" . $val . "'";
        }
        
        $query = $this->db->getQueryBuilder()
                ->sum('value')
                ->from($metric)
                ->where($where);

        $groupBy = "time(1d) tz('" . $timezone . "')";
        if ($granularity == self::GRANULARITY_HOURLY) {
            $groupBy = "time(1h) tz('" . $timezone . "')";
        } else if ($granularity == self::GRANULARITY_DAILY) {
            $groupBy = "time(1d) tz('" . $timezone . "')";
        } else if ($granularity == self::GRANULARITY_WEEKLY) {
            $groupBy = "time(1w) tz('" . $timezone . "')";
        }
        $query->groupBy($groupBy);
        
        return $query->getResultSet()->getPoints();        
    }
1347020
protected function mapResults(Metric $metric, array $results)
    {
        $results = Collection::make($results);

        return $results->map(function ($point) use ($metric) {
            if (!$point->value) {
                $point->value = $metric->default_value;
            }

            if ($point->value === 0 && $metric->default_value != $point->value) {
                $point->value = $metric->default_value;
            }

            $point->value = round($point->value, $metric->places);

            return $point;
        });
    }
1138881
@Override
	public void register(Metric metric, String metricName, AbstractMetricGroup group) {
		synchronized (lock) {
			if (isShutdown()) {
				LOG.warn("Cannot register metric, because the MetricRegistry has already been shut down.");
			} else {
				if (reporters != null) {
					for (int i = 0; i < reporters.size(); i++) {
						MetricReporter reporter = reporters.get(i);
						try {
							if (reporter != null) {
								FrontMetricGroup front = new FrontMetricGroup<AbstractMetricGroup<?>>(i, group);
								reporter.notifyOfAddedMetric(metric, metricName, front);
							}
						} catch (Exception e) {
							LOG.warn("Error while registering metric.", e);
						}
					}
				}
				try {
					if (queryService != null) {
						queryService.addMetric(metricName, metric, group);
					}
				} catch (Exception e) {
					LOG.warn("Error while registering metric.", e);
				}
				try {
					if (metric instanceof View) {
						if (viewUpdater == null) {
							viewUpdater = new ViewUpdater(executor);
						}
						viewUpdater.notifyOfAddedView((View) metric);
					}
				} catch (Exception e) {
					LOG.warn("Error while registering metric.", e);
				}
			}
		}
	}
1230826
def set_metric(slug, value, category=None, expire=None, date=None):
    """"""
    get_r().set_metric(slug, value, category=category, expire=expire, date=date)