LogMetricDemo.java

Download LogMetricDemo.java

 1: package com.wpollock;
 2: 
 3: import com.codahale.metrics.*;
 4: import org.slf4j.Logger;
 5: import org.slf4j.LoggerFactory;
 6: 
 7: import java.util.Random;
 8: import java.util.concurrent.TimeUnit;
 9: 
10: /**
11:  * Demo of Logging and Metrics collection.
12:  * This is a trivial but complete example of using SLF4J for
13:  * logging, and dropwizard.io Metrics package.
14:  *
15:  * For logging the output goes to the console.  The console
16:  * logger is called "simple" and can be configured in several
17:  * ways; here I use the simplelogger.properties file.
18:  * (SLF4J is used by many Maven plugins; to avoid finding unused
19:  * types and versions the POM must list those plugins and add an
20:  * "exclude" section.  Using "mvn dependency:tree", I found
21:  * three such plugins.
22:  *
23:  * For metrics, we use a single "meter" type metric and it
24:  * too is reported to the console (so non-GUI).  You can also
25:  * use Graphite GUI console by changed the reporter.
26:  *
27:  * @author Wayne Pollock
28:  */
29: public class LogMetricDemo {
30:     final static MetricRegistry metrics = new MetricRegistry();
31:     final static Meter requests = metrics.meter("requests");
32:     final static Logger logger = LoggerFactory.getLogger(LogMetricDemo.class);
33: 
34:     public static void main( String[] args )  {
35:         logger.info("Application Starting");
36: 
37:         // Configure metrics output to send non-GUI report to console:
38:         ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics)
39:                 .convertRatesTo(TimeUnit.SECONDS)
40:                 .convertDurationsTo(TimeUnit.MILLISECONDS)
41:                 .build();
42:         reporter.start(3, TimeUnit.SECONDS);  // produce report every 3s
43: 
44:         for (int i = 0; i < 10; ++i) {
45:             try {
46:                 handleRequest(i);
47:             } catch (InterruptedException e) {
48:                 return;
49:             }
50:         }
51:         reporter.close();
52:     }
53: 
54:     /**
55:      * Fake method that "handles" requests to demonstrate logging
56:      * and metrics.
57:      * @param i the iteration number
58:      */
59:     static void handleRequest(int i) throws InterruptedException {
60:         logger.trace("Entered handleRequest(" + i + ")");
61:         requests.mark();
62:         // ... handle request here ...
63:         Random random = new Random();
64: 
65:         int delayInMillis = random.nextInt(1000); // 0..1 second
66:             Thread.sleep(delayInMillis);
67: 
68:             logger.trace("Exited handleRequest(" + i + ")");
69:     }
70: }