Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.yammer.dropwizard.jetty;
  
  // TODO: 10/12/11 <coda> -- write tests for AsyncRequestLog
  
 
 import java.util.List;
A non-blocking, asynchronous org.eclipse.jetty.server.RequestLog implementation which implements a subset of the functionality of org.eclipse.jetty.server.NCSARequestLog. Log entries are added to an in-memory queue and an offline thread handles the responsibility of batching them to disk. The date format is fixed, UTC time zone is fixed, and latency is always logged.
 
 public class AsyncRequestLog extends AbstractLifeCycle implements RequestLog {
     private static final AtomicInteger THREAD_COUNTER = new AtomicInteger();
     private static final Log LOG = Log.forClass(AsyncRequestLog.class);
     private static final int BATCH_SIZE = 10000;
 
     private class Dispatcher implements Runnable {
         private volatile boolean running = true;
         private final List<Stringstatements = new ArrayList<String>();
 
         @Override
         public void run() {
             while () {
                 try {
                     .add(.take());
                     .drainTo();
                     for (String statement : ) {
                         .println(statement);
                     }
                     .flush();
                     .clear();
                 } catch (InterruptedException ignored) {
                     Thread.currentThread().interrupt();
                 }
             }
         }
 
         public void stop() {
             this. = true;
         }
     }
 
     private static final ThreadLocal<DateCacheDATE_CACHE = new ThreadLocal<DateCache>() {
         @Override
         protected DateCache initialValue() {
             final DateCache cache = new DateCache("dd/MMM/yyyy:HH:mm:ss Z",
                                                   Locale.getDefault());
             cache.setTimeZoneID("UTC");
             return cache;
         }
     };
 
     private final BlockingQueue<Stringqueue;
     private final String filenamePattern;
     private final int numberOfFilesToRetain;
     private final Thread dispatchThread;
     private final Dispatcher dispatcher;
     private PrintWriter writer;

    
Creates a new AsyncRequestLog.

Parameters:
filenamePattern The filename pattern to which the log statements will be written. If filenamePattern contains the string yyyy_mm_dd, the file will be rotated every day, with yyyy_mm_dd being replaced by the year, month, and day. If filenamePattern is null, statements will be logged to STDOUT.
numberOfFilesToRetain If filenamePattern is to be rotated, the number of total log files (including the active one) to be kept.
 
     public AsyncRequestLog(String filenamePatternint numberOfFilesToRetain) {
         this. = filenamePattern;
         this. = numberOfFilesToRetain;
         this. = null;
         this. = new LinkedBlockingQueue<String>();
         this. = new Dispatcher();
         this. = new Thread();
         .setName("async-request-log-dispatcher-" + .incrementAndGet());
         .setDaemon(true);
     }
    @Override
    @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed""UseOfSystemOutOrSystemErr"})
    protected void doStart() throws Exception {
        if ( == null) {
            this. = new PrintWriter(.);
        } else {
            final RolloverFileOutputStream outputStream = new RolloverFileOutputStream(
                    ,
                    true,
                    ,
                    TimeZone.getTimeZone("UTC"));
            this. = new PrintWriter(outputStream);
            .info("Opened {}"outputStream.getDatedFilename());
        }
        .start();
    }
    @Override
    protected void doStop() throws Exception {
        .stop();
        if ( != null) {
            .close();
        }
    }
    @Override
    public void log(Request requestResponse response) {
        // copied almost entirely from NCSARequestLog
        final StringBuilder buf = new StringBuilder(256);
        String address = request.getHeader(.);
        if (address == null) {
            address = request.getRemoteAddr();
        }
        buf.append(address);
        buf.append(" - ");
        final Authentication authentication = request.getAuthentication();
        if (authentication instanceof Authentication.User) {
            buf.append(((Authentication.Userauthentication).getUserIdentity()
                                                             .getUserPrincipal()
                                                             .getName());
        } else {
            buf.append(" - ");
        }
        buf.append(" [");
        buf.append(.get().format(request.getTimeStamp()));
        buf.append("] \"");
        buf.append(request.getMethod());
        buf.append(' ');
        buf.append(request.getUri().toString());
        buf.append(' ');
        buf.append(request.getProtocol());
        buf.append("\" ");
        if (request.getAsyncContinuation().isInitial()) {
            int status = response.getStatus();
            if (status <= 0) {
                status = 404;
            }
            buf.append((char) ('0' + ((status / 100) % 10)));
            buf.append((char) ('0' + ((status / 10) % 10)));
            buf.append((char) ('0' + (status % 10)));
        } else {
            buf.append("Async");
        }
        final long responseLength = response.getContentCount();
        if (responseLength >= 0) {
            buf.append(' ');
            if (responseLength > 99999) {
                buf.append(responseLength);
            } else {
                if (responseLength > 9999) {
                    buf.append((char) ('0' + ((responseLength / 10000) % 10)));
                }
                if (responseLength > 999) {
                    buf.append((char) ('0' + ((responseLength / 1000) % 10)));
                }
                if (responseLength > 99) {
                    buf.append((char) ('0' + ((responseLength / 100) % 10)));
                }
                if (responseLength > 9) {
                    buf.append((char) ('0' + ((responseLength / 10) % 10)));
                }
                buf.append((char) ('0' + (responseLength % 10)));
            }
            buf.append(' ');
        } else {
            buf.append(" - ");
        }
        final long now = System.currentTimeMillis();
        final long dispatchTime = request.getDispatchTime();
        buf.append(' ');
        buf.append(now - ((dispatchTime == 0) ? request.getTimeStamp() : dispatchTime));
        buf.append(' ');
        buf.append(now - request.getTimeStamp());
        .add(buf.toString());
    }
New to GrepCode? Check out our FAQ X