001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.util.log4j;
016    
017    import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
018    import com.liferay.portal.kernel.util.PropsKeys;
019    import com.liferay.portal.kernel.util.PropsUtil;
020    import com.liferay.portal.kernel.util.ServerDetector;
021    import com.liferay.portal.kernel.util.StreamUtil;
022    import com.liferay.portal.kernel.util.StringPool;
023    import com.liferay.portal.kernel.util.StringUtil;
024    
025    import java.io.IOException;
026    import java.io.InputStream;
027    import java.io.Reader;
028    import java.io.StringReader;
029    
030    import java.net.URL;
031    
032    import java.util.Enumeration;
033    import java.util.HashMap;
034    import java.util.HashSet;
035    import java.util.List;
036    import java.util.Map;
037    import java.util.Set;
038    
039    import org.apache.log4j.Level;
040    import org.apache.log4j.LogManager;
041    import org.apache.log4j.Logger;
042    import org.apache.log4j.xml.DOMConfigurator;
043    
044    import org.dom4j.Document;
045    import org.dom4j.Element;
046    import org.dom4j.io.SAXReader;
047    
048    /**
049     * @author Brian Wing Shun Chan
050     */
051    public class Log4JUtil {
052    
053            public static void configureLog4J(URL url) {
054                    if (url == null) {
055                            return;
056                    }
057    
058                    String urlContent = _getURLContent(url);
059    
060                    if (urlContent == null) {
061                            return;
062                    }
063    
064                    // See LPS-6029 and LPS-8865
065    
066                    if (!ServerDetector.isJBoss()) {
067                            DOMConfigurator domConfigurator = new DOMConfigurator();
068    
069                            Reader urlReader = new StringReader(urlContent);
070    
071                            domConfigurator.doConfigure(
072                                    urlReader, LogManager.getLoggerRepository());
073                    }
074    
075                    Set<String> currentLoggerNames = new HashSet<String>();
076    
077                    Enumeration<Logger> enu = LogManager.getCurrentLoggers();
078    
079                    while (enu.hasMoreElements()) {
080                            Logger logger = enu.nextElement();
081    
082                            currentLoggerNames.add(logger.getName());
083                    }
084    
085                    try {
086                            SAXReader saxReader = new SAXReader();
087    
088                            Reader urlReader = new StringReader(urlContent);
089    
090                            Document document = saxReader.read(urlReader, url.toExternalForm());
091    
092                            Element rootElement = document.getRootElement();
093    
094                            List<Element> categoryElements = rootElement.elements("category");
095    
096                            for (Element categoryElement : categoryElements) {
097                                    String name = categoryElement.attributeValue("name");
098    
099                                    Element priorityElement = categoryElement.element("priority");
100    
101                                    String priority = priorityElement.attributeValue("value");
102    
103                                    setLevel(name, priority);
104                            }
105                    }
106                    catch (Exception e) {
107                            e.printStackTrace();
108                    }
109            }
110    
111            public static void setLevel(String name, String priority) {
112                    Logger logger = Logger.getLogger(name);
113    
114                    logger.setLevel(Level.toLevel(priority));
115    
116                    java.util.logging.Logger jdkLogger = java.util.logging.Logger.getLogger(
117                            name);
118    
119                    jdkLogger.setLevel(_getJdkLevel(priority));
120            }
121    
122            /**
123             * @see {@link com.liferay.portal.util.FileImpl#getBytes(InputStream, int,
124             *      boolean)}
125             */
126            private static byte[] _getBytes(InputStream inputStream)
127                    throws IOException {
128    
129                    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream =
130                            new UnsyncByteArrayOutputStream();
131    
132                    StreamUtil.transfer(inputStream, unsyncByteArrayOutputStream, -1, true);
133    
134                    return unsyncByteArrayOutputStream.toByteArray();
135            }
136    
137            private static java.util.logging.Level _getJdkLevel(String priority) {
138                    if (priority.equalsIgnoreCase(Level.DEBUG.toString())) {
139                            return java.util.logging.Level.FINE;
140                    }
141                    else if (priority.equalsIgnoreCase(Level.ERROR.toString())) {
142                            return java.util.logging.Level.SEVERE;
143                    }
144                    else if (priority.equalsIgnoreCase(Level.WARN.toString())) {
145                            return java.util.logging.Level.WARNING;
146                    }
147                    else {
148                            return java.util.logging.Level.INFO;
149                    }
150            }
151    
152            private static String _getURLContent(URL url) {
153                    Map<String, String> variables = new HashMap<String, String>();
154    
155                    variables.put("liferay.home", PropsUtil.get(PropsKeys.LIFERAY_HOME));
156    
157                    String urlContent = null;
158    
159                    InputStream inputStream = null;
160    
161                    try {
162                            inputStream = url.openStream();
163    
164                            byte[] bytes = _getBytes(inputStream);
165    
166                            urlContent = new String(bytes, StringPool.UTF8);
167                    }
168                    catch (Exception e) {
169                            e.printStackTrace();
170    
171                            return null;
172                    }
173                    finally {
174                            StreamUtil.cleanUp(inputStream);
175                    }
176    
177                    for (Map.Entry<String, String> variable : variables.entrySet()) {
178                            urlContent = urlContent.replaceAll(
179                                    "@" + variable.getKey() + "@", variable.getValue());
180                    }
181    
182                    if (ServerDetector.getServerId() != null) {
183                            return urlContent;
184                    }
185    
186                    int x = urlContent.indexOf("<appender name=\"FILE\"");
187    
188                    int y = urlContent.indexOf("</appender>", x);
189    
190                    if (y != -1) {
191                            y = urlContent.indexOf("<", y + 1);
192                    }
193    
194                    if ((x != -1) && (y != -1)) {
195                            urlContent = urlContent.substring(0, x) + urlContent.substring(y);
196                    }
197    
198                    urlContent = StringUtil.replace(
199                            urlContent, "<appender-ref ref=\"FILE\" />", StringPool.BLANK);
200    
201                    return urlContent;
202            }
203    
204    }