Adding StatisticsΒΆ

This chapter describes how to add statistics to your plugins. The Traffic Server statistics API functions add your plugin’s statistics so you can view your plugin statistics as you would any other Traffic Server statistic, using traffic_ctl or the c:func:TSRecordDump API.

A statistic is an opaque object referred to by an integral handle returned by c:func:TSStatCreate. Only integer statistics are supported, so the type argument to c:func:TSStatCreate must be c:data:TS_RECORDDATATYPE_INT.

The following example shows how to add custom statistics to your plugin. Typically, you would attempt to find the statistic by name before creating is. This technique is useful if you want to increment a statistic from multiple plugins. Once you have a handle to the statistic, set the value with c:func:TSStatIntSet, and increment it with c:func:TSStatIntIncrement or c:func:TSStatIntDecrement.

#include <ts/ts.h>
#include <inttypes.h>
#include <time.h>

#define PLUGIN_NAME "statistics"

void
TSPluginInit(int /* argc */, const char * /* argv */ [])
{
  TSPluginRegistrationInfo info;

  info.plugin_name   = (char *)PLUGIN_NAME;
  info.vendor_name   = (char *)"Apache Software Foundation";
  info.support_email = (char *)"dev@trafficserver.apache.org";

  int id;
  const char name[] = "example.statistic.now";

  if (TSStatFindName(name, &id) == TS_ERROR) {
    id = TSStatCreate(name, TS_RECORDDATATYPE_INT, TS_STAT_NON_PERSISTENT, TS_STAT_SYNC_SUM);
    if (id == TS_ERROR) {
      TSError("%s: failed to register '%s'", PLUGIN_NAME, name);
      return;
    }
  }

  TSError("%s: %s registered with id %d", PLUGIN_NAME, name, id);

#if DEBUG
  TSReleaseAssert(id != TS_ERROR);
#endif

  // Set an initial value for our statistic.
  TSStatIntSet(id, time(nullptr));

  // Increment the statistic as time passes.
  TSStatIntIncrement(id, 1);

  TSDebug(PLUGIN_NAME, "%s is set to %" PRId64, name, TSStatIntGet(id));
  TSReleaseAssert(TSPluginRegister(&info) == TS_SUCCESS);
}