Saturday, August 12, 2017

Write Dropwizard metrics to a log file

Instead of using the Dropwizard URI to view the metrics of the methods that have been annotated by @Timed or @Metered on a need basis, you can also write the output to a log file.

The below changes needs to be made in the Dropwizard configuration xml file.
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:metrics="http://www.ryantenney.com/schema/metrics"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.ryantenney.com/schema/metrics
               http://www.ryantenney.com/schema/metrics/metrics-3.0.xsd">

    <!-- Registry should be defined in only one context XML file -->
    <metrics:metric-registry id="metrics"/>
    <metrics:health-check-registry id="healthCheck"/>
    <!-- annotation-driven must be included in all context files -->
    <metrics:annotation-driven metric-registry="metrics"
                               health-check-registry="healthCheck"/>
 
       <metrics:reporter type="slf4j" metric-registry="metrics" period="15m" logger="com.abc.zyx.metrics"/>

     
    <!-- (Optional) The metrics in this example require the metrics-jvm jar-->
    <metrics:register metric-registry="metrics">
        <bean metrics:name="jvm.gc" class="com.codahale.metrics.jvm.GarbageCollectorMetricSet" />
        <bean metrics:name="jvm.memory" class="com.codahale.metrics.jvm.MemoryUsageGaugeSet"/>
        <bean metrics:name="jvm.thread-states" class="com.codahale.metrics.jvm.ThreadStatesGaugeSet"/>
        <bean metrics:name="jvm.fd.usage" class="com.codahale.metrics.jvm.FileDescriptorRatioGauge"/>
    </metrics:register>

    <bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
        <property name="attributes">
            <map>
                <entry key="com.codahale.metrics.servlets.MetricsServlet.registry" value-ref="metrics"/>
                <entry key="com.codahale.metrics.servlets.HealthCheckServlet.registry" value-ref="healthCheck"/>
            </map>
        </property>
    </bean>

</beans>


And you need to also define a logger in log4j.xml or logback.xml file
logger="com.abc.zyx.metrics"