001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.rest;
014
015import static javax.servlet.http.HttpServletResponse.*;
016import static org.apache.juneau.internal.StringUtils.*;
017
018import java.text.*;
019import java.util.logging.*;
020
021import javax.servlet.http.*;
022
023import org.apache.juneau.internal.*;
024import org.apache.juneau.json.*;
025
026/**
027 * Logging utility class.
028 *
029 * <p>
030 * Subclasses can override these methods to tailor logging of HTTP requests.
031 * <br>Subclasses MUST implement a no-arg public constructor.
032 *
033 * <h5 class='section'>See Also:</h5>
034 * <ul>
035 *    <li class='link'>{@doc juneau-rest-server.LoggingAndErrorHandling}
036 * </ul>
037 */
038public class BasicRestLogger implements RestLogger {
039
040   private final JuneauLogger logger = JuneauLogger.getLogger(getClass());
041
042   /**
043    * Returns the Java logger used for logging.
044    *
045    * <p>
046    * Subclasses can provide their own logger.
047    * The default implementation returns the logger created using <code>Logger.getLogger(getClass())</code>.
048    *
049    * @return The logger used for logging.
050    */
051   protected Logger getLogger() {
052      return logger;
053   }
054
055   @Override /* RestLogger */
056   public void setLevel(Level level) {
057      getLogger().setLevel(level);
058   }
059   
060   /**
061    * Log a message to the logger.
062    *
063    * <p>
064    * Subclasses can override this method if they wish to log messages using a library other than Java Logging
065    * (e.g. Apache Commons Logging).
066    *
067    * @param level The log level.
068    * @param cause The cause.
069    * @param msg The message to log.
070    * @param args Optional {@link MessageFormat}-style arguments.
071    */
072   @Override /* RestLogger */
073   public void log(Level level, Throwable cause, String msg, Object...args) {
074      msg = format(msg, args);
075      getLogger().log(level, msg, cause);
076   }
077
078   /**
079    * Log a message.
080    *
081    * <p>
082    * Equivalent to calling <code>log(level, <jk>null</jk>, msg, args);</code>
083    *
084    * @param level The log level.
085    * @param msg The message to log.
086    * @param args Optional {@link MessageFormat}-style arguments.
087    */
088   @Override /* RestLogger */
089   public void log(Level level, String msg, Object...args) {
090      log(level, null, msg, args);
091   }
092
093   /**
094    * Same as {@link #log(Level, String, Object...)} excepts runs the arguments through {@link JsonSerializer#DEFAULT_READABLE}.
095    *
096    * <p>
097    * Serialization of arguments do not occur if message is not logged, so it's safe to use this method from within
098    * debug log statements.
099    *
100    * <h5 class='section'>Example:</h5>
101    * <p class='bcode w800'>
102    *    logObjects(<jsf>DEBUG</jsf>, <js>"Pojo contents:\n{0}"</js>, myPojo);
103    * </p>
104    *
105    * @param level The log level.
106    * @param msg The message to log.
107    * @param args Optional {@link MessageFormat}-style arguments.
108    */
109   @Override /* RestLogger */
110   public void logObjects(Level level, String msg, Object...args) {
111      for (int i = 0; i < args.length; i++)
112         args[i] = SimpleJsonSerializer.DEFAULT_READABLE.toStringObject(args[i]);
113      log(level, null, msg, args);
114   }
115
116   /**
117    * Callback method for logging errors during HTTP requests.
118    *
119    * <p>
120    * Typically, subclasses will override this method and log errors themselves.
121    *
122    * <p>
123    * The default implementation simply logs errors to the <code>RestServlet</code> logger.
124    *
125    * <p>
126    * Here's a typical implementation showing how stack trace hashing can be used to reduce log file sizes...
127    * <p class='bcode w800'>
128    *    <jk>protected void</jk> onError(HttpServletRequest req, HttpServletResponse res, RestException e, <jk>boolean</jk> noTrace) {
129    *       String qs = req.getQueryString();
130    *       String msg = <js>"HTTP "</js> + req.getMethod() + <js>" "</js> + e.getStatus() + <js>" "</js> + req.getRequestURI() + (qs == <jk>null</jk> ? <js>""</js> : <js>"?"</js> + qs);
131    *       <jk>int</jk> c = e.getOccurrence();
132    *
133    *       <jc>// REST_useStackTraceHashes is disabled, so we have to log the exception every time.</jc>
134    *       <jk>if</jk> (c == 0)
135    *          myLogger.log(Level.<jsf>WARNING</jsf>, <jsm>format</jsm>(<js>"[%s] %s"</js>, e.getStatus(), msg), e);
136    *
137    *       <jc>// This is the first time we've countered this error, so log a stack trace
138    *       // unless ?noTrace was passed in as a URL parameter.</jc>
139    *       <jk>else if</jk> (c == 1 &amp;&amp; ! noTrace)
140    *          myLogger.log(Level.<jsf>WARNING</jsf>, <jsm>format</jsm>(<js>"[%h.%s.%s] %s"</js>, e.hashCode(), e.getStatus(), c, msg), e);
141    *
142    *       <jc>// This error occurred before.
143    *       // Only log the message, not the stack trace.</jc>
144    *       <jk>else</jk>
145    *          myLogger.log(Level.<jsf>WARNING</jsf>, <jsm>format</jsm>(<js>"[%h.%s.%s] %s, %s"</js>, e.hashCode(), e.getStatus(), c, msg, e.getLocalizedMessage()));
146    *    }
147    * </p>
148    *
149    * @param req The servlet request object.
150    * @param res The servlet response object.
151    * @param e Exception indicating what error occurred.
152    */
153   @Override /* RestLogger */
154   public void onError(HttpServletRequest req, HttpServletResponse res, RestException e) {
155      if (shouldLog(req, res, e)) {
156         String qs = req.getQueryString();
157         String msg = "HTTP " + req.getMethod() + " " + e.getStatus() + " " + req.getRequestURI() + (qs == null ? "" : "?" + qs);
158         int c = e.getOccurrence();
159         if (shouldLogStackTrace(req, res, e)) {
160            msg = '[' + Integer.toHexString(e.hashCode()) + '.' + e.getStatus() + '.' + c + "] " + msg;
161            log(Level.WARNING, e, msg);
162         } else {
163            msg = '[' + Integer.toHexString(e.hashCode()) + '.' + e.getStatus() + '.' + c + "] " + msg + ", " + e.getLocalizedMessage();
164            log(Level.WARNING, msg);
165         }
166      }
167   }
168
169   /**
170    * Returns <jk>true</jk> if the specified exception should be logged.
171    *
172    * <p>
173    * Subclasses can override this method to provide their own logic for determining when exceptions are logged.
174    *
175    * <p>
176    * The default implementation will return <jk>false</jk> if <js>"noTrace=true"</js> is passed in the query string
177    * or <code>No-Trace: true</code> is specified in the header.
178    *
179    * @param req The HTTP request.
180    * @param res The HTTP response.
181    * @param e The exception.
182    * @return <jk>true</jk> if exception should be logged.
183    */
184   protected boolean shouldLog(HttpServletRequest req, HttpServletResponse res, RestException e) {
185      if (isNoTrace(req) && ! isDebug(req))
186         return false;
187      return true;
188   }
189
190   /**
191    * Returns <jk>true</jk> if a stack trace should be logged for this exception.
192    *
193    * <p>
194    * Subclasses can override this method to provide their own logic for determining when stack traces are logged.
195    *
196    * <p>
197    * The default implementation will only log a stack trace if {@link RestException#getOccurrence()} returns
198    * <code>1</code> and the exception is not one of the following:
199    * <ul>
200    *    <li>{@link HttpServletResponse#SC_UNAUTHORIZED}
201    *    <li>{@link HttpServletResponse#SC_FORBIDDEN}
202    *    <li>{@link HttpServletResponse#SC_NOT_FOUND}
203    * </ul>
204    *
205    * @param req The HTTP request.
206    * @param res The HTTP response.
207    * @param e The exception.
208    * @return <jk>true</jk> if stack trace should be logged.
209    */
210   protected boolean shouldLogStackTrace(HttpServletRequest req, HttpServletResponse res, RestException e) {
211      if (e.getOccurrence() == 1) {
212         switch (e.getStatus()) {
213            case SC_UNAUTHORIZED:
214            case SC_FORBIDDEN:
215            case SC_NOT_FOUND:  return false;
216            default:            return true;
217         }
218      }
219      return false;
220   }
221
222   private static boolean isNoTrace(HttpServletRequest req) {
223      return contains(req.getHeader("No-Trace"), "true") || contains(req.getQueryString(), "noTrace=true");
224   }
225
226   private static boolean isDebug(HttpServletRequest req) {
227      return contains(req.getHeader("Debug"), "true");
228   }
229}