Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements.  See the NOTICE file distributed with
   * this work for additional information regarding copyright ownership.
   * The ASF licenses this file to You under the Apache License, Version 2.0
   * (the "License"); you may not use this file except in compliance with
   * the License.  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 
 package org.apache.catalina.valves;
 
 
 import java.util.Date;
 import java.util.List;
 
 
An implementation of the W3c Extended Log File Format. See http://www.w3.org/TR/WD-logfile.html for more information about the format. The following fields are supported:
  • c-dns: Client hostname
  • c-ip: Client ip address
  • bytes: bytes served
  • cs-method: request method
  • cs-uri: The full uri requested
  • cs-uri-query: The query string
  • cs-uri-stem: The uri without query string
  • date: The date in yyyy-mm-dd format for GMT
  • s-dns: The server dns entry
  • s-ip: The server ip address
  • cs(XXX): The value of header XXX from client to server
  • sc(XXX): The value of header XXX from server to client
  • sc-status: The status code
  • time: Time the request was served
  • time-taken: Time (in seconds) taken to serve the request
  • x-A(XXX): Pull XXX attribute from the servlet context
  • x-C(XXX): Pull the first cookie of the name XXX
  • x-O(XXX): Pull the all response header values XXX
  • x-R(XXX): Pull XXX attribute from the servlet request
  • x-S(XXX): Pull XXX attribute from the session
  • x-P(...): Call request.getParameter(...) and URLencode it. Helpful to capture certain POST parameters.
  • For any of the x-H(...) the following method will be called from the HttpServletRequestObject
  • x-H(authType): getAuthType
  • x-H(characterEncoding): getCharacterEncoding
  • x-H(contentLength): getContentLength
  • x-H(locale): getLocale
  • x-H(protocol): getProtocol
  • x-H(remoteUser): getRemoteUser
  • x-H(requestedSessionId): getGequestedSessionId
  • x-H(requestedSessionIdFromCookie): isRequestedSessionIdFromCookie
  • x-H(requestedSessionIdValid): isRequestedSessionIdValid
  • x-H(scheme): getScheme
  • x-H(secure): isSecure

Log rotation can be on or off. This is dictated by the rotatable property.

For UvNIX users, another field called checkExistsis also available. If set to true, the log file's existence will be checked before each logging. This way an external log rotator can move the file somewhere and tomcat will start with a new file.

For JMX junkies, a public method called rotate has been made available to allow you to tell this instance to move the existing log file to somewhere else start writing a new log file.

Conditional logging is also supported. This can be done with the condition property. If the value returned from ServletRequest.getAttribute(condition) yields a non-null value. The logging will be skipped.

For extended attributes coming from a getAttribute() call, it is you responsibility to ensure there are no newline or control characters.

Author(s):
Tim Funk
Peter Rossbach
Version:
$Revision: 1237 $ $Date: 2009-11-03 02:55:48 +0100 (Tue, 03 Nov 2009) $
    extends AccessLogValve
    implements Lifecycle {
    // ----------------------------------------------------- Instance Variables


    
The descriptive information about this implementation.
    protected static final String extendedAccessLogInfo =
        "org.apache.catalina.valves.ExtendedAccessLogValve/2.1";
    // ------------------------------------------------------------- Properties


    
Return descriptive information about this implementation.
    public String getInfo() {
        return ();
    }
    // --------------------------------------------------------- Public Methods
    // -------------------------------------------------------- Private Methods

    
Wrap the incoming value into quotes and escape any inner quotes with double quotes.

Parameters:
value - The value to wrap quotes around
Returns:
'-' if empty of null. Otherwise, toString() will be called on the object and the value will be wrapped in quotes and any quotes will be escaped with 2 sets of quotes.
    private String wrap(Object value) {
        String svalue;
        // Does the value contain a " ? If so must encode it
        if (value == null || "-".equals(value))
            return "-";
        try {
            svalue = value.toString();
            if ("".equals(svalue))
                return "-";
        } catch (Throwable e) {
            /* Log error */
            return "-";
        }
        /* Wrap all quotes in double quotes. */
        StringBuilder buffer = new StringBuilder(svalue.length() + 2);
        buffer.append('\'');
        int i = 0;
        while (i < svalue.length()) {
            int j = svalue.indexOf('\''i);
            if (j == -1) {
                buffer.append(svalue.substring(i));
                i = svalue.length();
            } else {
                buffer.append(svalue.substring(ij + 1));
                buffer.append('"');
                i = j + 2;
            }
        }
        buffer.append('\'');
        return buffer.toString();
    }

    
Open the new log file for the date specified by dateStamp.
    protected synchronized void open() {
        super.open();
        if (.length()==0) {
            .println("#Fields: " + );
            .println("#Version: 2.0");
            .println("#Software: " + ServerInfo.getServerInfo());
        }
    }
    // ------------------------------------------------------ Lifecycle Methods
    protected class DateElement implements AccessLogElement {
        private Date currentDate = new Date(0);
        
        private String currentDateString = null;
        
        
A date formatter to format a Date into a date in the format "yyyy-MM-dd".
        private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        
        public DateElement() {
            .setTimeZone(TimeZone.getTimeZone("GMT"));
        }
        
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            if ( != date) {
                synchronized (this) {
                    if ( != date) {
                         = .format(date);
                         = date;
                    }
                }
            }
            buf.append();            
        }
    }
    
    protected class TimeElement implements AccessLogElement {
        private Date currentDate = new Date(0);
        
        private String currentTimeString = null;
        
        
A date formatter to format a Date into a time in the format "kk:mm:ss" (kk is a 24-hour representation of the hour).
        private SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");
        public TimeElement() {
            .setTimeZone(TimeZone.getTimeZone("GMT"));
        }
        
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            if ( != date) {
                synchronized (this) {
                    if ( != date) {
                         = .format(date);
                         = date;
                    }
                }
            }
            buf.append();            
        }
    }
    
    protected class RequestHeaderElement implements AccessLogElement {
        private String header;
        
        public RequestHeaderElement(String header) {
            this. = header;
        }
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            buf.append(wrap(request.getHeader()));
        }
    }
    
    protected class ResponseHeaderElement implements AccessLogElement {
        private String header;
        
        public ResponseHeaderElement(String header) {
            this. = header;
        }
        
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            buf.append(wrap(response.getHeader()));
        }
    }
    
    protected class ServletContextElement implements AccessLogElement {
        private String attribute;
        
        public ServletContextElement(String attribute) {
            this. = attribute;
        }
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            buf.append(wrap(request.getContext().getServletContext()
                    .getAttribute()));
        }
    }
    
    protected class CookieElement implements AccessLogElement {
        private String name;
        
        public CookieElement(String name) {
            this. = name;
        }
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            Cookie[] c = request.getCookies();
            for (int i = 0; c != null && i < c.lengthi++) {
                if (.equals(c[i].getName())) {
                    buf.append(wrap(c[i].getValue()));
                }
            }
        }
    }
    
    
write a specific response header - x-O(xxx)
    protected class ResponseAllHeaderElement implements AccessLogElement {
        private String header;
        public ResponseAllHeaderElement(String header) {
            this. = header;
        }
        
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
           if (null != response) {
                String[] values = response.getHeaderValues();
                if(values.length > 0) {
                    StringBuilder buffer = new StringBuilder();
                    for (int i = 0; i < values.lengthi++) {
                        String string = values[i];
                        buffer.append(string) ;
                        if(i+1<values.length)
                            buffer.append(",");
                    }
                    buf.append(wrap(buffer.toString()));
                    return ;
                }
            }
            buf.append("-");
        }
    }
    
    protected class RequestAttributeElement implements AccessLogElement { 
        private String attribute;
        
        public RequestAttributeElement(String attribute) {
            this. = attribute;
        }
        
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            buf.append(wrap(request.getAttribute()));
        }        
    }
    
    protected class SessionAttributeElement implements AccessLogElement {
        private String attribute;
        
        public SessionAttributeElement(String attribute) {
            this. = attribute;
        }
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            HttpSession session = null;
            if (request != null) {
                session = request.getSession(false);
                if (session != null)
                    buf.append(wrap(session.getAttribute()));
            }
        }
    }
    
    protected class RequestParameterElement implements AccessLogElement {
        private String parameter;
        
        public RequestParameterElement(String parameter) {
            this. = parameter;
        }
        
urlEncode the given string. If null or empty, return null.
        private String urlEncode(String value) {
            if (null==value || value.length()==0) {
                return null;
            }
            return URLEncoder.encode(value);
        }   
        
        public void addElement(StringBuilder bufDate dateRequest request,
                Response responselong time) {
            buf.append(wrap(urlEncode(request.getParameter())));
        }
    }
    
    protected class PatternTokenizer {
        private StringReader sr = null;
        private StringBuilder buf = new StringBuilder();
        private boolean ended = false;
        private boolean subToken;
        private boolean parameter;
        
        public PatternTokenizer(String str) {
             = new StringReader(str);
        }
        
        public boolean hasSubToken() {
            return ;
        }
        
        public boolean hasParameter() {
            return ;
        }
        
        public String getToken() throws IOException {
            if()
                return null ;
            
            String result = null;
             = false;
             = false;
            
            int c = .read();
            while (c != -1) {
                switch (c) {
                case ' ':
                    result = .toString();
                     = new StringBuilder();
                    .append((charc);
                    return result;
                case '-':
                    result = .toString();
                     = new StringBuilder();
                     = true;
                    return result;
                case '(':
                    result = .toString();
                     = new StringBuilder();
                     = true;
                    return result;
                case ')':
                    result = .toString();
                     = new StringBuilder();
                    break;
                default:
                    .append((charc);
                }
                c = .read();
            }
             = true;
            if (.length() != 0) {
                return .toString();
            } else {
                return null;
            }
        }
        
        public String getParameter()throws IOException {
            String result;
            if (!) {
                return null;
            }
             = false;
            int c = .read();
            while (c != -1) {
                if (c == ')') {
                    result = .toString();
                     = new StringBuilder();
                    return result;
                }
                .append((charc);
                c = .read();
            }
            return null;
        }
        
        public String getWhiteSpaces() throws IOException {
            if(isEnded())
                return "" ;
            StringBuilder whiteSpaces = new StringBuilder();
            if (.length() > 0) {
                whiteSpaces.append();
                 = new StringBuilder();
            }
            int c = .read();
            while (Character.isWhitespace((charc)) {
                whiteSpaces.append((charc);
                c = .read();
            }
            if (c == -1) {
                 = true;
            } else {
                .append((charc);
            }
            return whiteSpaces.toString();
        }
        
        public boolean isEnded() {
            return ;
        }
        
        public String getRemains() throws IOException {
            StringBuilder remains = new StringBuilder();
            for(int c = .read(); c != -1; c = .read()) {
                remains.append((charc);
            }
            return remains.toString();
        }
        
    }
    
    protected AccessLogElement[] createLogElements() {
            ..debug("decodePattern, pattern =" + );
        }
        List<AccessLogElementlist = new ArrayList<AccessLogElement>();
        PatternTokenizer tokenizer = new PatternTokenizer();
        try {
            // Ignore leading whitespace.
            tokenizer.getWhiteSpaces();
            if (tokenizer.isEnded()) {
                return null;
            }
            String token = tokenizer.getToken();
            while (token != null) {
                if (..isDebugEnabled()) {
                    ..debug("token = " + token);
                }
                AccessLogElement element = getLogElement(tokentokenizer);
                if (element == null) {
                    break;
                }
                list.add(element);
                String whiteSpaces = tokenizer.getWhiteSpaces();
                if (whiteSpaces.length() > 0) {
                    list.add(new StringElement(whiteSpaces));
                }
                if (tokenizer.isEnded()) {
                    break;
                }
                token = tokenizer.getToken();
            }
            if (..isDebugEnabled()) {
                ..debug("finished decoding with element size of: " + list.size());
            }
            return (AccessLogElement[]) list.toArray(new AccessLogElement[0]);
        } catch (IOException e) {
            return null;
        }
    }
    
    protected AccessLogElement getLogElement(String tokenPatternTokenizer tokenizerthrows IOException {
        if ("date".equals(token)) {
            return new DateElement();
        } else if ("time".equals(token)) {
            if (tokenizer.hasSubToken()) {
                String nextToken = tokenizer.getToken();
                if ("taken".equals(nextToken)) {
                    return new ElapsedTimeElement(false);                
                }
            } else {
                return new TimeElement();
            }
        } else if ("bytes".equals(token)) {
            return new ByteSentElement(true);
        } else if ("cached".equals(token)) {
            /* I don't know how to evaluate this! */
            return new StringElement("-");
        } else if ("c".equals(token)) {
            String nextToken = tokenizer.getToken();
            if ("ip".equals(nextToken)) {
                return new RemoteAddrElement();
            } else if ("dns".equals(nextToken)) {
                return new HostElement();
            }
        } else if ("s".equals(token)) {
            String nextToken = tokenizer.getToken();
            if ("ip".equals(nextToken)) {
                return new LocalAddrElement();
            } else if ("dns".equals(nextToken)) {
                return new AccessLogElement() {
                    public void addElement(StringBuilder bufDate date,
                            Request requestResponse responselong time) {
                        String value;
                        try {
                            value = InetAddress.getLocalHost().getHostName();
                        } catch (Throwable e) {
                            value = "localhost";
                        }
                        buf.append(value);
                    }
                };
            }
        } else if ("cs".equals(token)) {
            return getClientToServerElement(tokenizer);
        } else if ("sc".equals(token)) {
            return getServerToClientElement(tokenizer);
        } else if ("sr".equals(token) || "rs".equals(token)) {
            return getProxyElement(tokenizer);
        } else if ("x".equals(token)) {
            return getXParameterElement(tokenizer);
        }
        return null;
    }
    
            PatternTokenizer tokenizerthrows IOException {
        if (tokenizer.hasSubToken()) {
            String token = tokenizer.getToken();
            if ("method".equals(token)) {
                return new MethodElement();
            } else if ("uri".equals(token)) {
                if (tokenizer.hasSubToken()) {
                    token = tokenizer.getToken();
                    if ("stem".equals(token)) {
                        return new RequestURIElement();
                    } else if ("query".equals(token)) {
                        return new AccessLogElement() {
                            public void addElement(StringBuilder bufDate date,
                                    Request requestResponse response,
                                    long time) {
                                String query = request.getQueryString();
                                if (query != null) {
                                    buf.append(query);
                                } else {
                                    buf.append('-');
                                }
                            }
                        };
                    }
                } else {
                    return new AccessLogElement() {
                        public void addElement(StringBuilder bufDate date,
                                Request requestResponse responselong time) {
                            String query = request.getQueryString();
                            if (query == null) {
                                buf.append(request.getRequestURI());
                            } else {
                                buf.append(request.getRequestURI());
                                buf.append('?');
                                buf.append(request.getQueryString());
                            }
                        }
                    };
                }
            }
        } else if (tokenizer.hasParameter()) {
            String parameter = tokenizer.getParameter();
            if (parameter == null) {
                return null;
            }
            return new RequestHeaderElement(parameter);
        }
        return null;
    }
    
            PatternTokenizer tokenizerthrows IOException {
        if (tokenizer.hasSubToken()) {
            String token = tokenizer.getToken();
            if ("status".equals(token)) {
                return new HttpStatusCodeElement();
            } else if ("comment".equals(token)) {
                return new StringElement("?");
            }
        } else if (tokenizer.hasParameter()) {
            String parameter = tokenizer.getParameter();
            if (parameter == null) {
                return null;
            }
            return new ResponseHeaderElement(parameter);
        }
        return null;
    }
    
    protected AccessLogElement getProxyElement(PatternTokenizer tokenizer)
        throws IOException {
        String token = null;
        if (tokenizer.hasSubToken()) {
            token = tokenizer.getToken();
            return new StringElement("-");
        } else if (tokenizer.hasParameter()) {
            tokenizer.getParameter();
            return new StringElement("-");
        }
        return null;
    }
    
            throws IOException {
        if (!tokenizer.hasSubToken()) {
            return null;
        }
        String token = tokenizer.getToken();
        if (!tokenizer.hasParameter()) {
            return null;
        }
        String parameter = tokenizer.getParameter();
        if (parameter == null) {
            return null;
        }
        if ("A".equals(token)) {
            return new ServletContextElement(parameter);
        } else if ("C".equals(token)) {
            return new CookieElement(parameter);
        } else if ("R".equals(token)) {
            return new RequestAttributeElement(parameter);
        } else if ("S".equals(token)) {
            return new SessionAttributeElement(parameter);
        } else if ("H".equals(token)) {
            return getServletRequestElement(parameter);
        } else if ("P".equals(token)) {
            return new RequestParameterElement(parameter);
        } else if ("O".equals(token)) {
            return new ResponseAllHeaderElement(parameter);
        }
        return null;
    }
    
    protected AccessLogElement getServletRequestElement(String parameter) {
        if ("authType".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap(request.getAuthType()));
                }
            };
        } else if ("remoteUser".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap(request.getRemoteUser()));
                }
            };
        } else if ("requestedSessionId".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap(request.getRequestedSessionId()));
                }
            };
        } else if ("requestedSessionIdFromCookie".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap(""
                            + request.isRequestedSessionIdFromCookie()));
                }
            };
        } else if ("requestedSessionIdValid".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap("" + request.isRequestedSessionIdValid()));
                }
            };
        } else if ("contentLength".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap("" + request.getContentLength()));
                }
            };
        } else if ("characterEncoding".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap(request.getCharacterEncoding()));
                }
            };
        } else if ("locale".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap(request.getLocale()));
                }
            };
        } else if ("protocol".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap(request.getProtocol()));
                }
            };
        } else if ("scheme".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(request.getScheme());
                }
            };
        } else if ("secure".equals(parameter)) {
            return new AccessLogElement() {
                public void addElement(StringBuilder bufDate date,
                        Request requestResponse responselong time) {
                    buf.append(wrap("" + request.isSecure()));
                }
            };
        }
        return null;
    }
        
New to GrepCode? Check out our FAQ X