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