001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.util.log4j;
016    
017    import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
018    import com.liferay.portal.kernel.log.LogFactory;
019    import com.liferay.portal.kernel.log.LogFactoryUtil;
020    import com.liferay.portal.kernel.util.PropsKeys;
021    import com.liferay.portal.kernel.util.PropsUtil;
022    import com.liferay.portal.kernel.util.ServerDetector;
023    import com.liferay.portal.kernel.util.StreamUtil;
024    import com.liferay.portal.kernel.util.StringPool;
025    import com.liferay.portal.kernel.util.StringUtil;
026    
027    import java.io.IOException;
028    import java.io.InputStream;
029    import java.io.Reader;
030    import java.io.StringReader;
031    
032    import java.net.URL;
033    
034    import java.util.Enumeration;
035    import java.util.HashMap;
036    import java.util.HashSet;
037    import java.util.List;
038    import java.util.Map;
039    import java.util.Set;
040    import java.util.concurrent.ConcurrentHashMap;
041    
042    import org.apache.log4j.Level;
043    import org.apache.log4j.LogManager;
044    import org.apache.log4j.Logger;
045    import org.apache.log4j.xml.DOMConfigurator;
046    
047    import org.dom4j.Document;
048    import org.dom4j.Element;
049    import org.dom4j.io.SAXReader;
050    
051    /**
052     * @author Brian Wing Shun Chan
053     */
054    public class Log4JUtil {
055    
056            public static void configureLog4J(ClassLoader classLoader) {
057                    configureLog4J(classLoader.getResource("META-INF/portal-log4j.xml"));
058                    configureLog4J(
059                            classLoader.getResource("META-INF/portal-log4j-ext.xml"));
060            }
061    
062            public static void configureLog4J(URL url) {
063                    if (url == null) {
064                            return;
065                    }
066    
067                    String urlContent = _getURLContent(url);
068    
069                    if (urlContent == null) {
070                            return;
071                    }
072    
073                    // See LPS-6029, LPS-8865, and LPS-24280
074    
075                    DOMConfigurator domConfigurator = new DOMConfigurator();
076    
077                    Reader urlReader = new StringReader(urlContent);
078    
079                    domConfigurator.doConfigure(
080                            urlReader, LogManager.getLoggerRepository());
081    
082                    Set<String> currentLoggerNames = new HashSet<String>();
083    
084                    Enumeration<Logger> enu = LogManager.getCurrentLoggers();
085    
086                    while (enu.hasMoreElements()) {
087                            Logger logger = enu.nextElement();
088    
089                            currentLoggerNames.add(logger.getName());
090                    }
091    
092                    try {
093                            SAXReader saxReader = new SAXReader();
094    
095                            Reader reader = new StringReader(urlContent);
096    
097                            Document document = saxReader.read(reader, url.toExternalForm());
098    
099                            Element rootElement = document.getRootElement();
100    
101                            List<Element> categoryElements = rootElement.elements("category");
102    
103                            for (Element categoryElement : categoryElements) {
104                                    String name = categoryElement.attributeValue("name");
105    
106                                    Element priorityElement = categoryElement.element("priority");
107    
108                                    String priority = priorityElement.attributeValue("value");
109    
110                                    setLevel(name, priority, false);
111                            }
112                    }
113                    catch (Exception e) {
114                            e.printStackTrace();
115                    }
116            }
117    
118            public static Map<String, String> getCustomLogSettings() {
119                    return new HashMap<String, String>(_customLogSettings);
120            }
121    
122            public static void initLog4J(
123                    String serverId, String liferayHome, ClassLoader classLoader,
124                    LogFactory logFactory, Map<String, String> customLogSettings) {
125    
126                    ServerDetector.init(serverId);
127    
128                    _liferayHome = liferayHome;
129    
130                    configureLog4J(classLoader);
131    
132                    try {
133                            LogFactoryUtil.setLogFactory(logFactory);
134                    }
135                    catch (Exception e) {
136                            e.printStackTrace();
137                    }
138    
139                    for (String name : customLogSettings.keySet()) {
140                            String priority = customLogSettings.get(name);
141    
142                            setLevel(name, priority, false);
143                    }
144            }
145    
146            public static void setLevel(String name, String priority, boolean custom) {
147                    Logger logger = Logger.getLogger(name);
148    
149                    logger.setLevel(Level.toLevel(priority));
150    
151                    java.util.logging.Logger jdkLogger = java.util.logging.Logger.getLogger(
152                            name);
153    
154                    jdkLogger.setLevel(_getJdkLevel(priority));
155    
156                    if (custom) {
157                            _customLogSettings.put(name, priority);
158                    }
159            }
160    
161            /**
162             * @see {@link com.liferay.portal.util.FileImpl#getBytes(InputStream, int,
163             *      boolean)}
164             */
165            private static byte[] _getBytes(InputStream inputStream)
166                    throws IOException {
167    
168                    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream =
169                            new UnsyncByteArrayOutputStream();
170    
171                    StreamUtil.transfer(inputStream, unsyncByteArrayOutputStream, -1, true);
172    
173                    return unsyncByteArrayOutputStream.toByteArray();
174            }
175    
176            private static java.util.logging.Level _getJdkLevel(String priority) {
177                    if (priority.equalsIgnoreCase(Level.DEBUG.toString())) {
178                            return java.util.logging.Level.FINE;
179                    }
180                    else if (priority.equalsIgnoreCase(Level.ERROR.toString())) {
181                            return java.util.logging.Level.SEVERE;
182                    }
183                    else if (priority.equalsIgnoreCase(Level.WARN.toString())) {
184                            return java.util.logging.Level.WARNING;
185                    }
186                    else {
187                            return java.util.logging.Level.INFO;
188                    }
189            }
190    
191            private static String _getLiferayHome() {
192                    if (_liferayHome == null) {
193                            _liferayHome = PropsUtil.get(PropsKeys.LIFERAY_HOME);
194                    }
195    
196                    return _liferayHome;
197            }
198            private static String _getURLContent(URL url) {
199                    Map<String, String> variables = new HashMap<String, String>();
200    
201                    variables.put("liferay.home", _getLiferayHome());
202    
203                    String urlContent = null;
204    
205                    InputStream inputStream = null;
206    
207                    try {
208                            inputStream = url.openStream();
209    
210                            byte[] bytes = _getBytes(inputStream);
211    
212                            urlContent = new String(bytes, StringPool.UTF8);
213                    }
214                    catch (Exception e) {
215                            e.printStackTrace();
216    
217                            return null;
218                    }
219                    finally {
220                            StreamUtil.cleanUp(inputStream);
221                    }
222    
223                    for (Map.Entry<String, String> variable : variables.entrySet()) {
224                            urlContent = urlContent.replaceAll(
225                                    "@" + variable.getKey() + "@", variable.getValue());
226                    }
227    
228                    if (ServerDetector.getServerId() != null) {
229                            return urlContent;
230                    }
231    
232                    int x = urlContent.indexOf("<appender name=\"FILE\"");
233    
234                    int y = urlContent.indexOf("</appender>", x);
235    
236                    if (y != -1) {
237                            y = urlContent.indexOf("<", y + 1);
238                    }
239    
240                    if ((x != -1) && (y != -1)) {
241                            urlContent = urlContent.substring(0, x) + urlContent.substring(y);
242                    }
243    
244                    urlContent = StringUtil.replace(
245                            urlContent, "<appender-ref ref=\"FILE\" />", StringPool.BLANK);
246    
247                    return urlContent;
248            }
249    
250            private static Map<String, String> _customLogSettings =
251                    new ConcurrentHashMap<String, String>();
252            private static String _liferayHome;
253    
254    }