001
014
015 package com.liferay.util.log4j;
016
017 import com.liferay.portal.kernel.util.ServerDetector;
018
019 import java.net.URL;
020
021 import java.util.Enumeration;
022 import java.util.HashSet;
023 import java.util.Iterator;
024 import java.util.Set;
025
026 import org.apache.log4j.Level;
027 import org.apache.log4j.LogManager;
028 import org.apache.log4j.Logger;
029 import org.apache.log4j.xml.DOMConfigurator;
030
031 import org.dom4j.Document;
032 import org.dom4j.Element;
033 import org.dom4j.io.SAXReader;
034
035
038 public class Log4JUtil {
039
040 public static void configureLog4J(URL url) {
041 if (url == null) {
042 return;
043 }
044
045
046
047 if (!ServerDetector.isJBoss()) {
048 DOMConfigurator.configure(url);
049 }
050
051 Set<String> currentLoggerNames = new HashSet<String>();
052
053 Enumeration<Logger> enu = LogManager.getCurrentLoggers();
054
055 while (enu.hasMoreElements()) {
056 Logger logger = enu.nextElement();
057
058 currentLoggerNames.add(logger.getName());
059 }
060
061 try {
062 SAXReader reader = new SAXReader();
063
064 Document doc = reader.read(url);
065
066 Element root = doc.getRootElement();
067
068 Iterator<Element> itr = root.elements("category").iterator();
069
070 while (itr.hasNext()) {
071 Element category = itr.next();
072
073 String name = category.attributeValue("name");
074 String priority =
075 category.element("priority").attributeValue("value");
076
077 setLevel(name, priority);
078 }
079 }
080 catch (Exception e) {
081 e.printStackTrace();
082 }
083 }
084
085 public static void setLevel(String name, String priority) {
086 Logger logger = Logger.getLogger(name);
087
088 logger.setLevel(Level.toLevel(priority));
089
090 java.util.logging.Logger jdkLogger = java.util.logging.Logger.getLogger(
091 name);
092
093 jdkLogger.setLevel(_getJdkLevel(priority));
094 }
095
096 private static java.util.logging.Level _getJdkLevel(String priority) {
097 if (priority.equalsIgnoreCase(Level.DEBUG.toString())) {
098 return java.util.logging.Level.FINE;
099 }
100 else if (priority.equalsIgnoreCase(Level.ERROR.toString())) {
101 return java.util.logging.Level.SEVERE;
102 }
103 else if (priority.equalsIgnoreCase(Level.WARN.toString())) {
104 return java.util.logging.Level.WARNING;
105 }
106 else {
107 return java.util.logging.Level.INFO;
108 }
109 }
110
111 }