Sling Metrics bundle provides integration with Dropwizard Metrics library which provides a toolkit to capture runtime performance statistics in your application.
import org.apache.sling.metrics.Counter;
import org.apache.sling.metrics.MetricsService;
@Reference
private MetricsService metricsService;
private Counter counter;
@Activate
private void activate(){
counter = metricsService.counter("sessionCounter");
}
public void onSessionCreation(){
counter.increment();
}
To make use of MetricsService
org.apache.sling.metrics.MetricsService
Refer to Metric Getting Started guide to see how various types of Metric instances can be used. Note that when using Sling Commons Metrics bundle class names belong to org.apache.sling.commons.metrics
package
Sling Metrics bundle provides its own Metric classes which are modelled on Dropwizard Metrics library. The metric interfaces defined by Sling bundle only provides methods related to data collection.
Further it provides a MetricsService
which enables creation of different type of Metrics like Meter, Timer, Counter and Histogram.
MetricsService
in case it starts adding appreciable overhead. Turning on and off can also be done on individual metric basis.It also allows us to later extend the type of data collected. For e.g. we can also collect TimerSeries type of data for each metric without modifying the caller logic.
Sling Metrics bundle also registers the MetricRegistry
instance with OSGi service registry. The instance registered has a service property name
set to sling
(so as allow distinguishing from any other registered MetricRegistry
instance). It can be used to get direct access to Dropwizard Metric API if required.
@Reference(target = "(name=sling)")
private MetricRegistry registry;
Also the wrapper Metric instance can be converted to actual instance via adaptTo
calls.
import org.apache.sling.commons.metrics.Counter
Counter counter = metricService.counter("login");
com.codahale.metrics.Counter = counter.adaptTo(com.codahale.metrics.Counter.class)
A Web Console plugin is also provided which is accessible at http://localhost:8080/system/console/slingmetrics. It lists down all registered Metric instances and their state.
The plugin lists all Metric instances from any MetricRegistry
instance found in the OSGi service registry. If the MetricRegistry
service has a name
property defined then that would be prefixed to the Metric names from that registry. This allows use of same name in different registry instances.
Add following Maven dependency to your pom.xml:
<dependency>
<groupId>org.apache.sling</groupId>
<artifactId>org.apache.sling.commons.metrics</artifactId>
<version>1.0.0</version>
</dependency>
Or download from here