22
33import java .util .Map ;
44import java .util .concurrent .ConcurrentHashMap ;
5+ import java .util .concurrent .TimeUnit ;
6+
7+ import org .slf4j .LoggerFactory ;
58
69import com .codahale .metrics .Meter ;
710import com .codahale .metrics .Metric ;
811import com .codahale .metrics .MetricRegistry ;
912import com .codahale .metrics .Timer ;
13+ import com .codahale .metrics .jvm .CachedThreadStatesGaugeSet ;
14+ import com .codahale .metrics .jvm .GarbageCollectorMetricSet ;
15+ import com .codahale .metrics .jvm .MemoryUsageGaugeSet ;
16+ import com .codahale .metrics .logback .InstrumentedAppender ;
1017
18+ import ch .qos .logback .classic .Logger ;
19+ import ch .qos .logback .classic .LoggerContext ;
20+ // {{start:metrics}}
1121public class Metrics {
12- private static final MetricRegistry registry ;
22+ /*
23+ * Use a concurrent map to cache metrics we generate on the fly.
24+ * For example we generate status code metrics on the fly.
25+ */
1326 private static final Map <String , Metric > metricCache = new ConcurrentHashMap <>();
27+ private static final MetricRegistry registry ;
1428 static {
1529 registry = new MetricRegistry ();
30+ registry .register ("gc" , new GarbageCollectorMetricSet ());
31+ registry .register ("threads" , new CachedThreadStatesGaugeSet (10 , TimeUnit .SECONDS ));
32+ registry .register ("memory" , new MemoryUsageGaugeSet ());
33+
34+ // Logback metrics
35+ final LoggerContext factory = (LoggerContext ) LoggerFactory .getILoggerFactory ();
36+ final Logger root = factory .getLogger (Logger .ROOT_LOGGER_NAME );
37+ final InstrumentedAppender metrics = new InstrumentedAppender (registry );
38+ metrics .setContext (root .getLoggerContext ());
39+ metrics .start ();
40+ root .addAppender (metrics );
1641
1742 // Register reporters here.
1843 }
@@ -24,9 +49,9 @@ public static MetricRegistry registry() {
2449 public static Timer timer (String first , String ... keys ) {
2550 String key = MetricRegistry .name (first , keys );
2651 return (Timer ) metricCache .computeIfAbsent (key , (String metricName ) -> {
27- Timer metric = new Timer ();
28- registry .register (metricName , metric );
29- return metric ;
52+ Timer metric = new Timer ();
53+ registry .register (metricName , metric );
54+ return metric ;
3055 });
3156 }
3257
@@ -39,3 +64,4 @@ public static Meter meter(String first, String... keys) {
3964 });
4065 }
4166}
67+ // {{end:metrics}}
0 commit comments