/home/wpollock1/public_html/AJava/LogAndMetricsDemo/src/main/java/com/wpollock/LogMetricDemo.java

package com.wpollock;

import com.codahale.metrics.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Demo of Logging and Metrics collection.
 * This is a trivial but complete example of using SLF4J for
 * logging, and dropwizard.io Metrics package.
 *
 * For logging the output goes to the console.  The console
 * logger is called "simple" and can be configured in several
 * ways; here I use the simplelogger.properties file.
 * (SLF4J is used by many Maven plugins; to avoid finding unused
 * types and versions the POM must list those plugins and add an
 * "exclude" section.  Using "mvn dependency:tree", I found
 * three such plugins.
 *
 * For metrics, we use a single "meter" type metric and it
 * too is reported to the console (so non-GUI).  You can also
 * use Graphite GUI console by changed the reporter.
 *
 * @author Wayne Pollock
 */
public class LogMetricDemo {
    final static MetricRegistry metrics = new MetricRegistry();
    final static Meter requests = metrics.meter("requests");
    final static Logger logger = LoggerFactory.getLogger(LogMetricDemo.class);

    public static void main( String[] args )  {
        logger.info("Application Starting");

        // Configure metrics output to send non-GUI report to console:
        ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics)
                .convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS)
                .build();
        reporter.start(3, TimeUnit.SECONDS);  // produce report every 3s

        for (int i = 0; i < 10; ++i) {
            try {
                handleRequest(i);
            } catch (InterruptedException e) {
                return;
            }
        }
        reporter.close();
    }

    /**
     * Fake method that "handles" requests to demonstrate logging
     * and metrics.
     * @param i the iteration number
     */
    static void handleRequest(int i) throws InterruptedException {
        logger.trace("Entered handleRequest(" + i + ")");
        requests.mark();
        // ... handle request here ...
        Random random = new Random();

        int delayInMillis = random.nextInt(1000); // 0..1 second
            Thread.sleep(delayInMillis);

            logger.trace("Exited handleRequest(" + i + ")");
    }
}