You're viewing **Apigee Edge** documentation.  
[Go to the
**Apigee X** documentation](http://cloud.google.com/apigee/docs). info

> [!NOTE]
> **Note:** This feature is not available to Apigee hybrid users. For more information, see [Compare Apigee products](https://cloud.google.com/apigee/docs/api-platform/get-started/compare-apigee-products).

![](https://docs.apigee.com/static/api-platform/images/icon_policy_statistics-collector.jpg)

### What

Enables you to collect statistics for data in a message, such as product ID, price, REST
action, client and target URL, and message length. The data can come from flow variables
predefined by Apigee or custom variables that you define.

The statistics data is passed to the analytics server, which analyzes the statistics and
generates reports. You can view the reports by using the Edge management UI or Edge API.

> [!WARNING]
> **Warning:** Only **one** Statistics Collector policy should be attached to a single API proxy. If there are multiple Statistics Collector policies in a proxy, then the last one to execute determines the data written to the analytics server.

## Samples

### Basic example

```
<StatisticsCollector name="publishPurchaseDetails">
  <Statistics>
    <Statistic name="productID" ref="product.id" type="string">999999</Statistic>
    <Statistic name="price" ref="product.price" type="string">0</Statistic>
  </Statistics>
</StatisticsCollector>
```

In this example, you collect statistical information about two custom variables:
product.id and product.price. On every request, the
Statistics Collector policy writes the value of these two variables to the analytics
server.

This example also sets an optional default value for each variable, where the default
value of product.id is 999999
and the default product.price
is 0. If a variable is undefined and you do not specify a default value, then no data is
recordeded for the variable. If you specify a default value, then the default value is
recorded when the variable is undefined.

After gathering statistical data, you can use the Edge management UI or API
to retrieve the statistics. When retrieving statistics, you reference the data collected for
these variables as productID
and price, respectively.

### Accessing statistics

In this example, you use the Edge management API to view the statistical data for the
collection called `productID`. This request builds a custom report for
product IDs based on the sum of message counts submitted for each product ID for each
day. Substitute your organization name for the variable `{org_name}`, and
substitute the email and password for your account on Apigee Edge for
`email:password`.

> [!NOTE]
> **Note:** You can also generate custom reports by selecting **Analytics \> Reports** in the Edge UI at [enterprise.apigee.com](https://enterprise.apigee.com). See [Manage custom reports](https://docs.apigee.com/api-platform/analytics/create-custom-reports) for more.

Set the `timeRange` parameter to include the time interval when your data was
collected. Data older than six months from the current date is not accessible by default. If
you want to access data older than six months, contact [Apigee Edge Support](https://docs.apigee.com/api-platform/troubleshoot/support).

```
$ curl https://api.enterprise.apigee.com/v1/o/{org_name}/environments/test/stats/productID?"select=sum(message_count)&timeRange=1/19/2015%2000:00~6/21/2015%2000:00&timeUnit=day"
-u email:password
```

In the response, the name
field contains the product ID and value shows the number of requests for each day:

```
{
  "environments" : [ {
    "dimensions" : [ {
      "metrics" : [ {
        "name" : "sum(message_count)",
        "values" : [ {
          "timestamp" : 1353369600000,
          "value" : "4.0"
        } ]
      } ],
      "name" : "52"
    }, {
      "metrics" : [ {
        "name" : "sum(message_count)",
        "values" : [ {
          "timestamp" : 1353369600000,
          "value" : "19.0"
        } ]
      } ],
      "name" : "14"
    }, ...
  } ],
  "metaData" : {
    "samplingRate" : "100"
  }
}
```

### Extracting data for collection

```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ExtractVariables async="false" continueOnError="false" enabled="true" name="GetWeatherData">
    <VariablePrefix>weather</VariablePrefix>
    <XMLPayload>
       <Namespaces>
          <Namespace prefix="yweather">http://xml.weather.yahoo.com/ns/rss/1.0</Namespace>
       </Namespaces>
       <Variable name="location" type="string">
          <XPath>/rss/channel/yweather:location/@city</XPath>
       </Variable>
       <Variable name="condition" type="string">
          <XPath>/rss/channel/item/yweather:condition/@text</XPath>
       </Variable>
    </XMLPayload>
</ExtractVariables>
```

The Statistics Collector policy requires that the data collected be stored in variables.
These variables can be predefined by Apigee, or custom variables that you define.

In this example, you use the Extract Variables policy to extract data from an XML payload
that contains weather information. This policy:

- Extracts the name of the city and writes it to a variable named weather.location
- Extracts the current conditions and writes it to a variable named weather.condition

You can then use the Statistics Collector policy to gather information about the
variables, as shown below:

```
<StatisticsCollector name="publishPurchaseDetails">
  <Statistics>
    <Statistic name="weatherLocation" ref="weather.location" type="string"></Statistic>
    <Statistic name="weatherCondition" ref="weather.condition" type="string"></Statistic>
  </Statistics>
</StatisticsCollector>
```

For a complete tutorial that shows how to extract data from an XML payload for the
Statistics Collector policy, see [Analyze API
message content using custom analytics](https://docs.apigee.com/api-platform/analytics/analyze-api-message-content-using-custom-analytics).

*** ** * ** ***

## About the Statistics Collector policy

When executed, the Statistics Collector policy records the current value of one or more
variables. These variables can be flow variables predefined by Apigee or custom variables that
you define. This data is written to the Edge analytics server.

To access the statistical data collected by the policy, you use the Edge API or the Edge
management UI. For example, you can use the Edge management UI to create a custom report that
shows the collected data in a variety of formats.

> [!NOTE]
> **NOTE**
>
> It takes about 30 minutes for a new custom dimension to be added to the database
> after the [Statistics
> Collector policy](https://docs.apigee.com/api-platform/reference/policies/statistics-collector-policy) is invoked for the first time, for each environment. For example, if a
> Statistics Collector proxy is invoked in the `test` environment, data for that custom
> dimension starts to be available in the `test` environment 30 minutes later,
> and the custom dimension will appear in the
> [custom reports](https://docs.apigee.com/api-platform/analytics/create-custom-reports) Dimensions
> drop-down list.
>
> If that Statistics Collector proxy is then called from the `prod`
> environment, it will be about 30 minutes before data for that custom dimension starts being
> available in the `prod` environment. From then on, data is available after the same
> time interval as other dimensions.

For a complete tutorial using the Statistics Collector policy, see [Analyze API
message content using custom analytics](https://docs.apigee.com/api-platform/analytics/analyze-api-message-content-using-custom-analytics).

### Where to put the policy

You can put a Statistics Collector policy in the request or response flow of an API
proxy. However, if you put multiple Statistics Collector policies in a proxy, then the last
one to execute determines the data written to the analytics server and data written by any
previous Statistics Collector policies is lost.

One scenario where you might have multiple Statistics Collector policies in an API proxy is
when you have one one in the request or response flow, and another in a fault handler. If a fault
occurs in the API proxy, then the Statistics Collector in the fault handler determines the data
collected. You can use that Statistics Collector to record information about the fault, or to
record any other information that you think necessary. The Statistics Collector in the fault
handler determines the data collected regardless of whether or not the Statistics Collector
in the request/response already executed.

For more, see [Handling
faults](https://docs.apigee.com/api-platform/fundamentals/fault-handling).

## Element reference

The element reference describes the elements and attributes of the Statistics Collector
policy.

```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<StatisticsCollector async="false" continueOnError="false" enabled="true" name="Statistics-Collector-1">
    <DisplayName>Statistics Collector 1</DisplayName>
    <Statistics>
        <Statistic name="statName" ref="varName" type="refDataType">defaultStatValue</Statistic>
    </Statistics>
</StatisticsCollector>
```

> [!WARNING]
> **Warning:** Do *not* create two statistics collectors whose names differ only by case, such as `statistics-collector` and `Statistics-Collector`, as then exporting data will result in a "duplicate column names" error.

## \<StatisticsCollector\> attributes

```
<StatisticsCollector async="false" continueOnError="false" enabled="true" name="Stats-1">
```

The following table describes attributes that are common to all policy parent elements:

| Attribute | Description | Default | Presence |
|---|---|---|---|
| `name` | The internal name of the policy. The value of the `name` attribute can contain letters, numbers, spaces, hyphens, underscores, and periods. This value cannot exceed 255 characters. Optionally, use the `<DisplayName>` element to label the policy in the management UI proxy editor with a different, natural-language name. | N/A | Required |
| `continueOnError` | Set to `false` to return an error when a policy fails. This is expected behavior for most policies. Set to `true` to have flow execution continue even after a policy fails. | false | Optional |
| `enabled` | Set to `true` to enforce the policy. Set to `false` to *turn off* the policy. The policy will not be enforced even if it remains attached to a flow. | true | Optional |
| `async` | This attribute is deprecated. | false | Deprecated |

## \<DisplayName\> element

Use in addition to the `name` attribute to label the policy in the
management UI proxy editor with a different, natural-language name.

```
<DisplayName>Policy Display Name</DisplayName>
```

| Default | N/A If you omit this element, the value of the policy's `name` attribute is used. |
| Presence | Optional |
| Type | String |
|---|---|

## \<Statistics\>/\<Statistic\> element

```
<Statistics>
    <Statistic name="statName" ref="varName" type="refDataType">defaultStatValue</Statistic>
</Statistics>
```

| Attribute | Description | Default | Presence |
|---|---|---|---|
| name | The name used to reference the data collected for the specified variable. When viewing analytics data, use this name to reference the data collected about the variable specified by the `ref` attribute. If the variable specified by `ref` is undefined on a request or response, then `defaultStatValue` specifies the value collected for the variable. If you omit the default value, no data is collected for the variable when the variable is undefined. **Naming restrictions** The following naming restrictions apply to custom analytics variables: - Names can include the following characters: a-z, 0-9, _ (underscore) - Names cannot include spaces. - Names cannot be `dsi`, `response_time`, `timekey`, or `timestamp`. - Case is ignored. - You cannot use the name of any predefined analytics metric, dimension, or filter listed on [Analytics metrics, dimensions, and filters reference](https://docs.apigee.com/api-platform/analytics/analytics-reference). - In addition to the above, keywords listed on the following page are not allowed: <https://www.postgresql.org/docs/8.1/static/sql-keywords-appendix.html> | N/A | Required |
| ref | The flow variable for which you are collecting statistics. This variable can be a flow variable predefined by Apigee or a custom variable that you define in your API proxy. The ref attribute often references a custom variable defined by the Extract Variables policy. See [Extract Variables policy](https://docs.apigee.com/api-platform/reference/policies/extract-variables-policy) for more. | N/A | Required |
| type | Specifies the data type of the variable specified by the ref attribute. Valid values are: string/integer/float/long/double/boolean. For data of type string, reference the statistical data as a *Dimension* in a custom report. For numerical data types (integer/float/long/double), reference the statistical data in a custom report as either a *Dimension* or a *Metric* . See [Manage custom reports](https://docs.apigee.com/api-platform/analytics/create-custom-reports) for more. The value of type can be omitted only if ref refers to a predefined Apigee flow variable or the type is declared in the XML payload of the Extract Variables policy. > [!NOTE] > **Note:** You cannot change the data type once Edge has begun to gather statistics. If you want to change the data type, create a new `<Statistic>` tag with a new name that references the same flow variable. | string | Optional |

## Error reference


This section describes the error messages and flow variables that are set when this policy
triggers an error. This information is important to know if you are developing fault rules for a
proxy. To learn more, see [What you need to know
about policy errors](https://docs.apigee.com/api-platform/fundamentals/what-you-need-know-about-policy-errors) and [Handling
faults](https://docs.apigee.com/api-platform/fundamentals/fault-handling).

### Runtime errors

None.

### Deployment errors

> [!IMPORTANT]
> Need help resolving an error? Click in the Fix column for detailed troubleshooting information.

> [!IMPORTANT]
> **Tip:** Use [API Monitoring](https://docs.apigee.com/api-monitoring) to investigate fault codes and diagnose issues faster. See [Set up a policy fault code alert](https://docs.apigee.com/api-monitoring/alerts-notifications#fault-code-alert) for an example. See [Fault code reference](https://docs.apigee.com/api-monitoring/fault-codes) for a complete list of all fault codes that you can handle with API Monitoring.

| Error name | Cause | Fix |
|---|---|---|
| `UnsupportedDatatype` | If the type of the variable specified by the ref attribute in the `<Statistic>` element of the Statistics Collector policy is unsupported, then the deployment of the API proxy fails. The supported data types are `string`, `integer`, `float`, `long`, `double`, and `boolean`. | [](https://docs.apigee.com/api-platform/troubleshoot/policies/deployment/stats-collector-deployment-errors#unsupporteddatatype) |
| `InvalidName` | If the name used to reference the data collected for the specified variable defined within the `<Statistic>` element of the Statistics Collector policy conflicts with a system-defined variable, then the deployment of the API proxy fails. Some of the known system-defined variables are `organization` and `environment`. | [](https://docs.apigee.com/api-platform/troubleshoot/policies/deployment/stats-collector-deployment-errors#invalidname) |
| `DatatypeMissing` | If the type of the variable specified by the `ref` attribute in the `<Statistic>` element of the Statistics Collector policy is missing, then the deployment of the API proxy fails. | [](https://docs.apigee.com/api-platform/troubleshoot/policies/deployment/stats-collector-deployment-errors#datatypemissing) |

### Fault variables

None.

<br />

## Schema

Each policy type is defined by an XML schema (`.xsd`). For reference, [policy schemas](https://github.com/apigee/api-platform-samples/tree/master/schemas/policy)
are available on GitHub.

## Related topics

For more information, see:

- [Analyze API
  message content using custom analytics](https://docs.apigee.com/api-platform/analytics/analyze-api-message-content-using-custom-analytics)
- [Manage custom reports](https://docs.apigee.com/api-platform/analytics/create-custom-reports)
- [Use the metrics APIs to measure API program performance](https://docs.apigee.com/api-platform/analytics/use-analytics-api-measure-api-program-performance)