1 17 18 package org.apache.geronimo.system.logging.log4j; 19 20 import java.io.BufferedReader ; 21 import java.io.IOException ; 22 import java.io.InputStreamReader ; 23 import java.io.FileNotFoundException ; 24 import java.net.URL ; 25 import java.net.URLConnection ; 26 27 import org.apache.commons.logging.Log; 28 import org.apache.commons.logging.LogFactory; 29 import org.apache.log4j.LogManager; 30 import org.apache.log4j.PropertyConfigurator; 31 import org.apache.log4j.spi.Configurator; 32 import org.apache.log4j.spi.LoggerRepository; 33 import org.apache.log4j.xml.DOMConfigurator; 34 35 40 public class URLConfigurator implements Configurator { 41 private static final Log log = LogFactory.getLog(URLConfigurator.class); 42 43 public static void configure(final URL url) { 44 new URLConfigurator().doConfigure(url, LogManager.getLoggerRepository()); 45 } 46 47 private Configurator getConfigurator(final URL url) throws FileNotFoundException { 48 String contentType = null; 49 50 URLConnection connection = null; 52 try { 53 connection = url.openConnection(); 54 contentType = connection.getContentType(); 55 if (log.isTraceEnabled()) { 56 log.trace("Content type: " + contentType); 57 } 58 } catch (FileNotFoundException e) { 59 throw e; 60 } catch (IOException e) { 61 log.warn("Could not determine content type from URL; ignoring", e); 62 } 63 if (contentType != null) { 64 if (contentType.toLowerCase().endsWith("/xml")) { 65 return new DOMConfigurator(); 66 } 67 } 68 69 String filename = url.getFile().toLowerCase(); 71 if (filename.endsWith(".xml")) { 72 return new DOMConfigurator(); 73 } else if (filename.endsWith(".properties")) { 74 return new PropertyConfigurator(); 75 } 76 77 if (connection != null) { 79 try { 80 BufferedReader reader = new BufferedReader (new InputStreamReader (connection.getInputStream())); 81 try { 82 String head = reader.readLine(); 83 if (head.startsWith("<?xml")) { 84 return new DOMConfigurator(); 85 } 86 } finally { 87 reader.close(); 88 } 89 } catch (IOException e) { 90 log.warn("Failed to check content header; ignoring", e); 91 } 92 } 93 94 log.warn("Unable to determine content type, using property configurator"); 95 return new PropertyConfigurator(); 96 } 97 98 public void doConfigure(final URL url, final LoggerRepository repo) { 99 if (log.isDebugEnabled()) { 100 log.debug("Configuring from URL: " + url); 101 } 102 103 Configurator delegate = null; 105 try { 106 delegate = getConfigurator(url); 107 } catch (FileNotFoundException e) { 108 return; 109 } 110 111 if (log.isTraceEnabled()) { 112 log.trace("Configuring Log4j using configurator: " + 113 delegate + ", repository: " + repo); 114 } 115 116 delegate.doConfigure(url, repo); 118 } 119 } 120 | Popular Tags |