Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.server;
 
 import java.io.Writer;
 
 
This RequestLog implementation outputs logs in the pseudo-standard NCSA common log format. Configuration options allow a choice between the standard Common Log Format (as used in the 3 log format) and the Combined Log Format (single log format). This log format can be output by most web servers, and almost all web log analysis software can understand these formats.

Org.apache.xbean.XBean:
element="ncsaLog"
 
 
 /* ------------------------------------------------------------ */
 
 public class NCSARequestLog extends AbstractLifeCycle implements RequestLog
 {
     private static final Logger LOG = Log.getLogger(NCSARequestLog.class);
 
     private String _filename;
     private boolean _extended;
     private boolean _append;
     private int _retainDays;
     private boolean _closeOut;
     private boolean _preferProxiedForAddress;
     private String _logDateFormat = "dd/MMM/yyyy:HH:mm:ss Z";
     private String _filenameDateFormat = null;
     private Locale _logLocale = Locale.getDefault();
     private String _logTimeZone = "GMT";
     private String[] _ignorePaths;
     private boolean _logLatency = false;
     private boolean _logCookies = false;
     private boolean _logServer = false;
     private boolean _logDispatch = false;
 
     private transient OutputStream _out;
     private transient OutputStream _fileOut;
     private transient DateCache _logDateCache;
     private transient PathMap _ignorePathMap;
     private transient Writer _writer;
 
     /* ------------------------------------------------------------ */
    
Create request log object with default settings.
 
     public NCSARequestLog()
     {
          = true;
          = true;
          = 31;
     }
 
     /* ------------------------------------------------------------ */
    
Create request log object with specified output file name.

Parameters:
filename the file name for the request log. This may be in the format expected by org.eclipse.jetty.util.RolloverFileOutputStream
 
     public NCSARequestLog(String filename)
     {
         = true;
         = true;
         = 31;
        setFilename(filename);
    }
    /* ------------------------------------------------------------ */
    
Set the output file name of the request log. The file name may be in the format expected by org.eclipse.jetty.util.RolloverFileOutputStream.

Parameters:
filename file name of the request log
    public void setFilename(String filename)
    {
        if (filename != null)
        {
            filename = filename.trim();
            if (filename.length() == 0)
                filename = null;
        }
         = filename;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the output file name of the request log.

Returns:
file name of the request log
    public String getFilename()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the file name of the request log with the expanded date wildcard if the output is written to the disk using org.eclipse.jetty.util.RolloverFileOutputStream.

Returns:
file name of the request log, or null if not applicable
    public String getDatedFilename()
    {
        if ( instanceof RolloverFileOutputStream)
            return ((RolloverFileOutputStream)).getDatedFilename();
        return null;
    }
    /* ------------------------------------------------------------ */
    
Set the timestamp format for request log entries in the file. If this is not set, the pre-formated request timestamp is used.

Parameters:
format timestamp format string
    public void setLogDateFormat(String format)
    {
         = format;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the timestamp format string for request log entries.

Returns:
timestamp format string.
    public String getLogDateFormat()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the locale of the request log.

Parameters:
logLocale locale object
    public void setLogLocale(Locale logLocale)
    {
         = logLocale;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the locale of the request log.

Returns:
locale object
    public Locale getLogLocale()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the timezone of the request log.

Parameters:
tz timezone string
    public void setLogTimeZone(String tz)
    {
         = tz;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the timezone of the request log.

Returns:
timezone string
    public String getLogTimeZone()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the number of days before rotated log files are deleted.

Parameters:
retainDays number of days to keep a log file
    public void setRetainDays(int retainDays)
    {
         = retainDays;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the number of days before rotated log files are deleted.

Returns:
number of days to keep a log file
    public int getRetainDays()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the extended request log format flag.

Parameters:
extended true - log the extended request information, false - do not log the extended request information
    public void setExtended(boolean extended)
    {
         = extended;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the extended request log format flag.

Returns:
value of the flag
    public boolean isExtended()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set append to log flag.

Parameters:
append true - request log file will be appended after restart, false - request log file will be overwritten after restart
    public void setAppend(boolean append)
    {
         = append;
    }
    /* ------------------------------------------------------------ */
    
Retrieve append to log flag.

Returns:
value of the flag
    public boolean isAppend()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set request paths that will not be logged.

Parameters:
ignorePaths array of request paths
    public void setIgnorePaths(String[] ignorePaths)
    {
         = ignorePaths;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the request paths that will not be logged.

Returns:
array of request paths
    public String[] getIgnorePaths()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Controls logging of the request cookies.

Parameters:
logCookies true - values of request cookies will be logged, false - values of request cookies will not be logged
    public void setLogCookies(boolean logCookies)
    {
         = logCookies;
    }
    /* ------------------------------------------------------------ */
    
Retrieve log cookies flag

Returns:
value of the flag
    public boolean getLogCookies()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Controls logging of the request hostname.

Parameters:
logServer true - request hostname will be logged, false - request hostname will not be logged
    public void setLogServer(boolean logServer)
    {
         = logServer;
    }
    /* ------------------------------------------------------------ */
    
Retrieve log hostname flag.

Returns:
value of the flag
    public boolean getLogServer()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Controls logging of request processing time.

Parameters:
logLatency true - request processing time will be logged false - request processing time will not be logged
    public void setLogLatency(boolean logLatency)
    {
         = logLatency;
    }
    /* ------------------------------------------------------------ */
    
Retrieve log request processing time flag.

Returns:
value of the flag
    public boolean getLogLatency()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Controls whether the actual IP address of the connection or the IP address from the X-Forwarded-For header will be logged.

Parameters:
preferProxiedForAddress true - IP address from header will be logged, false - IP address from the connection will be logged
    public void setPreferProxiedForAddress(boolean preferProxiedForAddress)
    {
         = preferProxiedForAddress;
    }
    
    /* ------------------------------------------------------------ */
    
Retrieved log X-Forwarded-For IP address flag.

Returns:
value of the flag
    public boolean getPreferProxiedForAddress()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the log file name date format.

    public void setFilenameDateFormat(String logFileDateFormat)
    {
         = logFileDateFormat;
    }
    /* ------------------------------------------------------------ */
    
Retrieve the file name date format string.

Returns:
the log File Date Format
    public String getFilenameDateFormat()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Controls logging of the request dispatch time

Parameters:
value true - request dispatch time will be logged false - request dispatch time will not be logged
    public void setLogDispatch(boolean value)
    {
         = value;
    }
    /* ------------------------------------------------------------ */
    
Retrieve request dispatch time logging flag

Returns:
value of the flag
    public boolean isLogDispatch()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Writes the request and response information to the output stream.

    public void log(Request requestResponse response)
    {
        try
        {
            if ( != null && .getMatch(request.getRequestURI()) != null)
                return;
            if ( == null)
                return;
            StringBuilder bufnew StringBuilder(256);
            if ()
            {
                buf.append(request.getServerName());
                buf.append(' ');
            }
            String addr = null;
            if ()
            {
                addr = request.getHeader(.);
            }
            if (addr == null)
                addr = request.getRemoteAddr();
            buf.append(addr);
            buf.append(" - ");
            Authentication authentication=request.getAuthentication();
            if (authentication instanceof Authentication.User)
                buf.append(((Authentication.User)authentication).getUserIdentity().getUserPrincipal().getName());
            else
                buf.append(" - ");
            buf.append(" [");
            if ( != null)
                buf.append(.format(request.getTimeStamp()));
            else
                buf.append(request.getTimeStampBuffer().toString());
            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");
            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(" - ");
            
            if ()
                logExtended(requestresponsebuf);
            if ()
            {
                Cookie[] cookies = request.getCookies();
                if (cookies == null || cookies.length == 0)
                    buf.append(" -");
                else
                {
                    buf.append(" \"");
                    for (int i = 0; i < cookies.lengthi++)
                    {
                        if (i != 0)
                            buf.append(';');
                        buf.append(cookies[i].getName());
                        buf.append('=');
                        buf.append(cookies[i].getValue());
                    }
                    buf.append('\"');
                }
            }
            if ( || )
            {
                long now = System.currentTimeMillis();
                if ()
                {   
                    long d = request.getDispatchTime();
                    buf.append(' ');
                    buf.append(now - (d==0 ? request.getTimeStamp():d));
                }
                if ()
                {
                    buf.append(' ');
                    buf.append(now - request.getTimeStamp());
                }
            }
            buf.append(.);
            String log = buf.toString();
            synchronized(this)
            {
                if (==null)
                    return;
                .write(log);
                .flush();
            }
        }
        catch (IOException e)
        {
            .warn(e);
        }
    }
    /* ------------------------------------------------------------ */
    
Writes extended request and response information to the output stream.

Parameters:
request request object
response response object
b StringBuilder to write to
Throws:
java.io.IOException
    protected void logExtended(Request request,
                               Response response,
                               StringBuilder bthrows IOException
    {
        String referer = request.getHeader(.);
        if (referer == null)
            b.append("\"-\" ");
        else
        {
            b.append('"');
            b.append(referer);
            b.append("\" ");
        }
        String agent = request.getHeader(.);
        if (agent == null)
            b.append("\"-\" ");
        else
        {
            b.append('"');
            b.append(agent);
            b.append('"');
        }
    }
    /* ------------------------------------------------------------ */
    
Set up request logging and open log file.

    @Override
    protected synchronized void doStart() throws Exception
    {
        if ( != null)
        {
             = new DateCache(,);
            .setTimeZoneID();
        }
        if ( != null)
        {
             = true;
            .info("Opened " + getDatedFilename());
        }
        else
             = .;
         = ;
        if ( != null && . > 0)
        {
             = new PathMap();
            for (int i = 0; i < .i++)
                .put([i],[i]);
        }
        else
             = null;
         = new OutputStreamWriter();
        super.doStart();
    }
    /* ------------------------------------------------------------ */
    
Close the log file and perform cleanup.

    @Override
    protected void doStop() throws Exception
    {
        synchronized (this)
        {
            super.doStop();
            try
            {
                if ( != null)
                    .flush();
            }
            catch (IOException e)
            {
                .ignore(e);
            }
            if ( != null && )
                try
                {
                    .close();
                }
                catch (IOException e)
                {
                    .ignore(e);
                }
             = null;
             = null;
             = false;
             = null;
             = null;
        }
    }
New to GrepCode? Check out our FAQ X