1 package info.magnolia.logging; 2 3 import info.magnolia.cms.core.SystemProperty; 4 import info.magnolia.cms.util.ConfigUtil; 5 6 import java.io.IOException ; 7 import java.io.InputStream ; 8 import java.util.HashMap ; 9 import java.util.Map ; 10 import java.util.Properties ; 11 12 import javax.servlet.ServletContext ; 13 14 import org.apache.commons.io.IOUtils; 15 import org.apache.commons.lang.StringUtils; 16 import org.apache.log4j.LogManager; 17 import org.apache.log4j.PropertyConfigurator; 18 import org.apache.log4j.xml.DOMConfigurator; 19 import org.w3c.dom.Document ; 20 21 22 47 public abstract class Log4jConfigurer { 48 49 52 public static final String LOG4J_CONFIG = "log4j.config"; 54 57 private Log4jConfigurer() { 58 } 60 61 67 public static void initLogging(ServletContext servletContext) { 68 69 log("Initializing Log4J"); 72 String log4jFileName = (String ) SystemProperty.getProperty(LOG4J_CONFIG); 73 if (StringUtils.isNotEmpty(log4jFileName)) { 74 boolean isXml = log4jFileName.toLowerCase().endsWith(".xml"); 76 log("Initializing Log4J from [" + log4jFileName + "]"); 78 InputStream stream = ConfigUtil.getConfigFile(log4jFileName); 79 80 String config; 81 try { 82 config = ConfigUtil.replaceTokens(stream); 83 } 84 catch (IOException e) { 85 log("Unable to initialize Log4J from [" + log4jFileName 87 + "], got a IOException " + e.getMessage()); 89 return; 90 } 91 92 if (isXml) { 94 Document document; 95 try { 96 Map dtds = new HashMap (); 97 dtds.put("log4j.dtd", "/org/apache/log4j/xml/log4j.dtd"); 98 document = ConfigUtil.string2DOM(config, dtds); 99 } 100 catch (Exception e) { 101 log("Unable to initialize Log4J from [" + log4jFileName 103 + "], got an Exception during reading the xml file " + e.getMessage()); 105 return; 106 } 107 DOMConfigurator.configure(document.getDocumentElement()); 108 } 109 else { 110 Properties properties = new Properties (); 111 try { 112 properties.load(IOUtils.toInputStream(config)); 113 } 114 catch (IOException e) { 115 log("Unable to initialize Log4J from [" + log4jFileName 117 + "], got an Exception during reading the properties file " + e.getMessage()); 119 return; 120 } 121 PropertyConfigurator.configure(log4jFileName); 122 } 123 124 } 125 } 126 127 131 public static void shutdownLogging(Map parameters) { 132 log("Shutting down Log4J"); try { 134 LogManager.shutdown(); 135 } 136 finally { 137 String param = (String ) parameters.get(SystemProperty.MAGNOLIA_ROOT_SYSPROPERTY); 139 if (StringUtils.isNotEmpty(param)) { 140 System.getProperties().remove(param); 141 } 142 } 143 } 144 145 149 public static void log(String message) { 150 System.out.println(message); 151 } 152 153 } 154 | Popular Tags |