All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.juneau.rest.RestLogger Maven / Gradle / Ivy

There is a newer version: 9.0.1
Show newest version
// ***************************************************************************************************************************
// * 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.juneau.rest;

import static javax.servlet.http.HttpServletResponse.*;
import static org.apache.juneau.internal.StringUtils.*;

import java.text.*;
import java.util.logging.*;

import javax.servlet.http.*;

import org.apache.juneau.internal.*;
import org.apache.juneau.json.*;
import org.apache.juneau.rest.annotation.*;

/**
 * Logging utility class.
 *
 * 

* Subclasses can override these methods to tailor logging of HTTP requests. * Subclasses MUST implement a no-arg public constructor. * *

* RestLoggers are associated with servlets/resources in one of the following ways: *

    *
  • The {@link RestResource#logger @RestResource.logger()} annotation. *
  • The {@link RestConfig#setLogger(Class)}/{@link RestConfig#setLogger(RestLogger)} methods. *
*/ public abstract class RestLogger { /** * Returns the Java logger used for logging. * *

* Subclasses can provide their own logger. * The default implementation returns the logger created using Logger.getLogger(getClass()). * * @return The logger used for logging. */ protected abstract Logger getLogger(); /** * Log a message to the logger. * *

* Subclasses can override this method if they wish to log messages using a library other than Java Logging * (e.g. Apache Commons Logging). * * @param level The log level. * @param cause The cause. * @param msg The message to log. * @param args Optional {@link MessageFormat}-style arguments. */ protected abstract void log(Level level, Throwable cause, String msg, Object...args); /** * Log a message. * *

* Equivalent to calling log(level, null, msg, args); * * @param level The log level. * @param msg The message to log. * @param args Optional {@link MessageFormat}-style arguments. */ protected void log(Level level, String msg, Object...args) { log(level, null, msg, args); } /** * Same as {@link #log(Level, String, Object...)} excepts runs the arguments through {@link JsonSerializer#DEFAULT_LAX_READABLE}. * *

* Serialization of arguments do not occur if message is not logged, so it's safe to use this method from within * debug log statements. * *

Example:
*

* logObjects(DEBUG, "Pojo contents:\n{0}", myPojo); *

* * @param level The log level. * @param msg The message to log. * @param args Optional {@link MessageFormat}-style arguments. */ protected void logObjects(Level level, String msg, Object...args) { for (int i = 0; i < args.length; i++) args[i] = JsonSerializer.DEFAULT_LAX_READABLE.toStringObject(args[i]); log(level, null, msg, args); } /** * Callback method for logging errors during HTTP requests. * *

* Typically, subclasses will override this method and log errors themselves. * *

* The default implementation simply logs errors to the RestServlet logger. * *

* Here's a typical implementation showing how stack trace hashing can be used to reduce log file sizes... *

* protected void onError(HttpServletRequest req, HttpServletResponse res, RestException e, boolean noTrace) { * String qs = req.getQueryString(); * String msg = "HTTP " + req.getMethod() + " " + e.getStatus() + " " + req.getRequestURI() + (qs == null ? "" : "?" + qs); * int c = e.getOccurrence(); * * // REST_useStackTraceHashes is disabled, so we have to log the exception every time. * if (c == 0) * myLogger.log(Level.WARNING, format("[%s] %s", e.getStatus(), msg), e); * * // This is the first time we've countered this error, so log a stack trace * // unless ?noTrace was passed in as a URL parameter. * else if (c == 1 && ! noTrace) * myLogger.log(Level.WARNING, format("[%h.%s.%s] %s", e.hashCode(), e.getStatus(), c, msg), e); * * // This error occurred before. * // Only log the message, not the stack trace. * else * myLogger.log(Level.WARNING, format("[%h.%s.%s] %s, %s", e.hashCode(), e.getStatus(), c, msg, e.getLocalizedMessage())); * } *

* * @param req The servlet request object. * @param res The servlet response object. * @param e Exception indicating what error occurred. */ protected void onError(HttpServletRequest req, HttpServletResponse res, RestException e) { if (shouldLog(req, res, e)) { String qs = req.getQueryString(); String msg = "HTTP " + req.getMethod() + " " + e.getStatus() + " " + req.getRequestURI() + (qs == null ? "" : "?" + qs); int c = e.getOccurrence(); if (shouldLogStackTrace(req, res, e)) { msg = '[' + Integer.toHexString(e.hashCode()) + '.' + e.getStatus() + '.' + c + "] " + msg; log(Level.WARNING, e, msg); } else { msg = '[' + Integer.toHexString(e.hashCode()) + '.' + e.getStatus() + '.' + c + "] " + msg + ", " + e.getLocalizedMessage(); log(Level.WARNING, msg); } } } /** * Returns true if the specified exception should be logged. * *

* Subclasses can override this method to provide their own logic for determining when exceptions are logged. * *

* The default implementation will return false if "noTrace=true" is passed in the query string * or No-Trace: true is specified in the header. * * @param req The HTTP request. * @param res The HTTP response. * @param e The exception. * @return true if exception should be logged. */ protected boolean shouldLog(HttpServletRequest req, HttpServletResponse res, RestException e) { if (isNoTrace(req) && ! isDebug(req)) return false; return true; } /** * Returns true if a stack trace should be logged for this exception. * *

* Subclasses can override this method to provide their own logic for determining when stack traces are logged. * *

* The default implementation will only log a stack trace if {@link RestException#getOccurrence()} returns * 1 and the exception is not one of the following: *

    *
  • {@link HttpServletResponse#SC_UNAUTHORIZED} *
  • {@link HttpServletResponse#SC_FORBIDDEN} *
  • {@link HttpServletResponse#SC_NOT_FOUND} *
* * @param req The HTTP request. * @param res The HTTP response. * @param e The exception. * @return true if stack trace should be logged. */ protected boolean shouldLogStackTrace(HttpServletRequest req, HttpServletResponse res, RestException e) { if (e.getOccurrence() == 1) { switch (e.getStatus()) { case SC_UNAUTHORIZED: case SC_FORBIDDEN: case SC_NOT_FOUND: return false; default: return true; } } return false; } private static boolean isNoTrace(HttpServletRequest req) { return "true".equals(req.getHeader("No-Trace")) || (req.getQueryString() != null && req.getQueryString().contains("noTrace=true")); } private static boolean isDebug(HttpServletRequest req) { return "true".equals(req.getHeader("Debug")); } /** * NO-OP logger. * *

* Disables all logging. * * @author James Bognar ([email protected]) */ public static class NoOp extends RestLogger { @Override /* RestLogger */ protected Logger getLogger() { return null; } @Override /* RestLogger */ protected void log(Level level, Throwable cause, String msg, Object...args) {} } /** * Default logger. * *

* Logs all messages to the logger returned by Logger.getLogger(getClass().getName()) */ public static class Normal extends RestLogger { private final JuneauLogger logger = JuneauLogger.getLogger(getClass()); @Override /* RestLogger */ protected Logger getLogger() { return logger; } @Override /* RestLogger */ protected void log(Level level, Throwable cause, String msg, Object...args) { msg = format(msg, args); getLogger().log(level, msg, cause); } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy