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'><a class="doclink" href="../../../../overview-summary.html#juneau-rest-server.LoggingAndErrorHandling">Overview &gt; juneau-rest-server &gt; Logging and Error Handling</a>
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   /**
056    * Log a message to the logger.
057    * 
058    * <p>
059    * Subclasses can override this method if they wish to log messages using a library other than Java Logging
060    * (e.g. Apache Commons Logging).
061    * 
062    * @param level The log level.
063    * @param cause The cause.
064    * @param msg The message to log.
065    * @param args Optional {@link MessageFormat}-style arguments.
066    */
067   @Override /* RestLogger */
068   public void log(Level level, Throwable cause, String msg, Object...args) {
069      msg = format(msg, args);
070      getLogger().log(level, msg, cause);
071   }
072
073   /**
074    * Log a message.
075    * 
076    * <p>
077    * Equivalent to calling <code>log(level, <jk>null</jk>, msg, args);</code>
078    * 
079    * @param level The log level.
080    * @param msg The message to log.
081    * @param args Optional {@link MessageFormat}-style arguments.
082    */
083   @Override /* RestLogger */
084   public void log(Level level, String msg, Object...args) {
085      log(level, null, msg, args);
086   }
087
088   /**
089    * Same as {@link #log(Level, String, Object...)} excepts runs the arguments through {@link JsonSerializer#DEFAULT_LAX_READABLE}.
090    * 
091    * <p>
092    * Serialization of arguments do not occur if message is not logged, so it's safe to use this method from within
093    * debug log statements.
094    * 
095    * <h5 class='section'>Example:</h5>
096    * <p class='bcode'>
097    *    logObjects(<jsf>DEBUG</jsf>, <js>"Pojo contents:\n{0}"</js>, myPojo);
098    * </p>
099    * 
100    * @param level The log level.
101    * @param msg The message to log.
102    * @param args Optional {@link MessageFormat}-style arguments.
103    */
104   @Override /* RestLogger */
105   public void logObjects(Level level, String msg, Object...args) {
106      for (int i = 0; i < args.length; i++)
107         args[i] = JsonSerializer.DEFAULT_LAX_READABLE.toStringObject(args[i]);
108      log(level, null, msg, args);
109   }
110
111   /**
112    * Callback method for logging errors during HTTP requests.
113    * 
114    * <p>
115    * Typically, subclasses will override this method and log errors themselves.
116    * 
117    * <p>
118    * The default implementation simply logs errors to the <code>RestServlet</code> logger.
119    * 
120    * <p>
121    * Here's a typical implementation showing how stack trace hashing can be used to reduce log file sizes...
122    * <p class='bcode'>
123    *    <jk>protected void</jk> onError(HttpServletRequest req, HttpServletResponse res, RestException e, <jk>boolean</jk> noTrace) {
124    *       String qs = req.getQueryString();
125    *       String msg = <js>"HTTP "</js> + req.getMethod() + <js>" "</js> + e.getStatus() + <js>" "</js> + req.getRequestURI() + (qs == <jk>null</jk> ? <js>""</js> : <js>"?"</js> + qs);
126    *       <jk>int</jk> c = e.getOccurrence();
127    * 
128    *       <jc>// REST_useStackTraceHashes is disabled, so we have to log the exception every time.</jc>
129    *       <jk>if</jk> (c == 0)
130    *          myLogger.log(Level.<jsf>WARNING</jsf>, <jsm>format</jsm>(<js>"[%s] %s"</js>, e.getStatus(), msg), e);
131    * 
132    *       <jc>// This is the first time we've countered this error, so log a stack trace
133    *       // unless ?noTrace was passed in as a URL parameter.</jc>
134    *       <jk>else if</jk> (c == 1 &amp;&amp; ! noTrace)
135    *          myLogger.log(Level.<jsf>WARNING</jsf>, <jsm>format</jsm>(<js>"[%h.%s.%s] %s"</js>, e.hashCode(), e.getStatus(), c, msg), e);
136    * 
137    *       <jc>// This error occurred before.
138    *       // Only log the message, not the stack trace.</jc>
139    *       <jk>else</jk>
140    *          myLogger.log(Level.<jsf>WARNING</jsf>, <jsm>format</jsm>(<js>"[%h.%s.%s] %s, %s"</js>, e.hashCode(), e.getStatus(), c, msg, e.getLocalizedMessage()));
141    *    }
142    * </p>
143    * 
144    * @param req The servlet request object.
145    * @param res The servlet response object.
146    * @param e Exception indicating what error occurred.
147    */
148   @Override /* RestLogger */
149   public void onError(HttpServletRequest req, HttpServletResponse res, RestException e) {
150      if (shouldLog(req, res, e)) {
151         String qs = req.getQueryString();
152         String msg = "HTTP " + req.getMethod() + " " + e.getStatus() + " " + req.getRequestURI() + (qs == null ? "" : "?" + qs);
153         int c = e.getOccurrence();
154         if (shouldLogStackTrace(req, res, e)) {
155            msg = '[' + Integer.toHexString(e.hashCode()) + '.' + e.getStatus() + '.' + c + "] " + msg;
156            log(Level.WARNING, e, msg);
157         } else {
158            msg = '[' + Integer.toHexString(e.hashCode()) + '.' + e.getStatus() + '.' + c + "] " + msg + ", " + e.getLocalizedMessage();
159            log(Level.WARNING, msg);
160         }
161      }
162   }
163
164   /**
165    * Returns <jk>true</jk> if the specified exception should be logged.
166    * 
167    * <p>
168    * Subclasses can override this method to provide their own logic for determining when exceptions are logged.
169    * 
170    * <p>
171    * The default implementation will return <jk>false</jk> if <js>"noTrace=true"</js> is passed in the query string
172    * or <code>No-Trace: true</code> is specified in the header.
173    * 
174    * @param req The HTTP request.
175    * @param res The HTTP response.
176    * @param e The exception.
177    * @return <jk>true</jk> if exception should be logged.
178    */
179   protected boolean shouldLog(HttpServletRequest req, HttpServletResponse res, RestException e) {
180      if (isNoTrace(req) && ! isDebug(req))
181         return false;
182      return true;
183   }
184
185   /**
186    * Returns <jk>true</jk> if a stack trace should be logged for this exception.
187    * 
188    * <p>
189    * Subclasses can override this method to provide their own logic for determining when stack traces are logged.
190    * 
191    * <p>
192    * The default implementation will only log a stack trace if {@link RestException#getOccurrence()} returns
193    * <code>1</code> and the exception is not one of the following:
194    * <ul>
195    *    <li>{@link HttpServletResponse#SC_UNAUTHORIZED}
196    *    <li>{@link HttpServletResponse#SC_FORBIDDEN}
197    *    <li>{@link HttpServletResponse#SC_NOT_FOUND}
198    * </ul>
199    * 
200    * @param req The HTTP request.
201    * @param res The HTTP response.
202    * @param e The exception.
203    * @return <jk>true</jk> if stack trace should be logged.
204    */
205   protected boolean shouldLogStackTrace(HttpServletRequest req, HttpServletResponse res, RestException e) {
206      if (e.getOccurrence() == 1) {
207         switch (e.getStatus()) {
208            case SC_UNAUTHORIZED:
209            case SC_FORBIDDEN:
210            case SC_NOT_FOUND:  return false;
211            default:            return true;
212         }
213      }
214      return false;
215   }
216
217   private static boolean isNoTrace(HttpServletRequest req) {
218      return contains(req.getHeader("No-Trace"), "true") || contains(req.getQueryString(), "noTrace=true");
219   }
220
221   private static boolean isDebug(HttpServletRequest req) {
222      return contains(req.getHeader("Debug"), "true");
223   }
224}