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

it.openutils.log4j.Log4jConfigurationServlet Maven / Gradle / Ivy

There is a newer version: 3.0.11
Show newest version
/*
 * Copyright 2005 Fabrizio Giustina..
 *
 * Licensed 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 it.openutils.log4j;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;


/**
 * A servlet used to dynamically adjust package logging levels while an application is running. NOTE: This servlet is
 * only aware of pre-configured packages and packages that contain objects that have logged at least one message since
 * application startup.
 * 

* web.xml configuration: *

* *
 * <servlet>
 *   <servlet-name>log4j</servlet-name>
 *   <display-name>Log4j configuration Servlet</display-name>
 *   <servlet-class>it.openutils.log4j.Log4jConfigurationServlet</servlet-class>
 * </servlet>
 * 
* *

* The fragment parameter can be added if you don't want a full xhtml page in output, but only the * content of the body tag, so that it can be used in portlets or struts tiles. *

* *
 * <servlet>
 *   <servlet-name>log4j</servlet-name>
 *   <display-name>Log4j configuration Servlet</display-name>
 *   <servlet-class>it.openutils.log4j.Log4jConfigurationServlet</servlet-class>
 *   <init-param>
 *     <param-name>fragment</param-name>
 *     <param-value>true</param-value>
 *   </init-param>
 * </servlet>
 * 
* * @author Luther E. Birdzell [email protected] * @author Yoav Shapira [email protected] * @author Fabrizio Giustina * @version $Id$ */ public class Log4jConfigurationServlet extends HttpServlet { /** * Stable serialVersionUID */ private static final long serialVersionUID = 64182; /** * The response content type: text/html */ private static final String CONTENT_TYPE = "text/html"; /** * Should not print html head and body? */ private static final String CONFIG_FRAGMENT = "fragment"; /** * The root appender. */ private static final String ROOT = "Root"; /** * The name of the class / package. */ private static final String PARAM_CLASS = "class"; /** * The logging level. */ private static final String PARAM_LEVEL = "level"; /** * Sort by level? */ private static final String PARAM_SORTBYLEVEL = "sortbylevel"; /** * All the log levels. */ private static final String[] LEVELS = new String[]{ Level.OFF.toString(), Level.FATAL.toString(), Level.ERROR.toString(), Level.WARN.toString(), Level.INFO.toString(), Level.DEBUG.toString(), Level.ALL.toString() }; /** * Don't include html head. */ private boolean isFragment; /** * Print the status of all current Logger s and an option to change their respective logging levels. * @param request a HttpServletRequest value * @param response a HttpServletResponse value * @exception ServletException if an error occurs * @exception IOException if an error occurs */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String className = request.getParameter(PARAM_CLASS); String level = request.getParameter(PARAM_LEVEL); if (className != null && level != null) { setClass(className, level); } String sortByLevelParam = request.getParameter(PARAM_SORTBYLEVEL); boolean sortByLevel = ("true".equalsIgnoreCase(sortByLevelParam) || "yes".equalsIgnoreCase(sortByLevelParam)); List loggers = getSortedLoggers(sortByLevel); int loggerNum = 0; PrintWriter out = response.getWriter(); if (!isFragment) { response.setContentType(CONTENT_TYPE); // print title and header printHeader(out, request); } // print scripts out.println("Refresh"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); // print the root Logger displayLogger(out, Logger.getRootLogger(), loggerNum++, request); // print the rest of the loggers Iterator iterator = loggers.iterator(); while (iterator.hasNext()) { displayLogger(out, iterator.next(), loggerNum++, request); } out.println(""); out.println("
"); out.println("Class"); out.println("*"); out.println("Level"); out.println("
"); out.println("Refresh"); if (!isFragment) { out.println(""); out.flush(); out.close(); } } /** * Change a Logger's level, then call doGet to refresh the page. * @param request a HttpServletRequest value * @param response a HttpServletResponse value * @exception ServletException if an error occurs * @exception IOException if an error occurs */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } /** * Print a Logger and its current level. * @param out the output writer. * @param logger the logger to output. * @param row the row number in the table this logger will appear in. * @param request the servlet request. */ private void displayLogger(PrintWriter out, Logger logger, int row, HttpServletRequest request) { String color = null; String loggerName = (logger.getName().equals("") ? ROOT : logger.getName()); color = ((row % 2) == 1) ? "even" : "odd"; out.println(""); // logger out.println(""); out.println(loggerName); out.println(""); // level inherited? out.println(""); if ((logger.getLevel() == null)) { out.println("*"); } out.println(""); // level and selection out.println(""); out.println("
"); printLevelSelector(out, logger.getEffectiveLevel().toString()); out.println(""); out.print(""); out.println("
"); out.println(""); out.println(""); } /** * Set a logger's level. * @param className class name of the logger to set. * @param level the level to set the logger to. * @return String return message for display. */ private synchronized String setClass(String className, String level) { Logger logger = null; try { logger = (ROOT.equalsIgnoreCase(className) ? Logger.getRootLogger() : Logger.getLogger(className)); logger.setLevel(Level.toLevel(level)); } catch (Throwable e) { System // permetti system.out .out.println("ERROR Setting LOG4J Logger:" + e); } return "Message Set For " + (logger.getName().equals("") ? ROOT : logger.getName()); } /** * Get a sorted list of all current loggers. * @param sortByLevel if true sort loggers by level instead of name. * @return List the list of sorted loggers. */ @SuppressWarnings("unchecked") private List getSortedLoggers(boolean sortByLevel) { Enumeration enm = LogManager.getCurrentLoggers(); List list = new ArrayList(); // Add all current loggers to the list while (enm.hasMoreElements()) { list.add(enm.nextElement()); } // sort the loggers Collections.sort(list, new LoggerComparator(sortByLevel)); return list; } /** * Prints the page header. * @param out The output writer * @param request The request */ private void printHeader(PrintWriter out, HttpServletRequest request) { out.println("Log4J Control Console"); out.println(""); out.println(""); out.println(""); out.println("

Log4J Control Console

"); } /** * Prints the Level select HTML. * @param out The output writer * @param currentLevel the current level for the log (the selected option). */ private void printLevelSelector(PrintWriter out, String currentLevel) { out.println(""); } /** * Compare the names of two Loggers. Used for sorting. */ private class LoggerComparator implements Comparator { /** * Sort by level? (default is sort by class name) */ private boolean sortByLevel; /** * instantiate a new LoggerComparator * @param sortByLevel if true sort loggers by level instead of name. */ public LoggerComparator(boolean sortByLevel) { this.sortByLevel = sortByLevel; } /** * Compare the names of two Loggers. * @param object1 an Object value * @param object2 an Object value * @return an int value */ public int compare(Logger logger1, Logger logger2) { if (!sortByLevel) { return logger1.getName().compareTo(logger2.getName()); } return logger1.getEffectiveLevel().toInt() - logger2.getEffectiveLevel().toInt(); } /** * Return true if the Object is a LoggerComparator instance. * @param object an Object value * @return a boolean value */ @Override public boolean equals(Object object) { if (!(object instanceof LoggerComparator)) { return false; } return this.sortByLevel == ((LoggerComparator) object).sortByLevel; } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return super.hashCode(); } } /** * {@inheritDoc} */ @Override public void init(ServletConfig config) throws ServletException { String fragmentParam = config.getInitParameter(CONFIG_FRAGMENT); isFragment = ("true".equalsIgnoreCase(fragmentParam) || "yes".equalsIgnoreCase(fragmentParam)); super.init(config); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy