001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017package org.apache.logging.log4j.util; 018 019import java.io.IOException; 020import java.net.URL; 021import java.util.Collection; 022import java.util.Enumeration; 023import java.util.HashSet; 024import java.util.Properties; 025import java.util.ServiceLoader; 026import java.util.concurrent.locks.Lock; 027import java.util.concurrent.locks.ReentrantLock; 028 029import org.apache.logging.log4j.Logger; 030import org.apache.logging.log4j.spi.Provider; 031import org.apache.logging.log4j.status.StatusLogger; 032 033/** 034 * <em>Consider this class private.</em> Utility class for Log4j {@link Provider}s. When integrating with an application 035 * container framework, any Log4j Providers not accessible through standard classpath scanning should 036 * {@link #loadProvider(java.net.URL, ClassLoader)} a classpath accordingly. 037 */ 038public final class ProviderUtil { 039 040 /** 041 * Resource name for a Log4j 2 provider properties file. 042 */ 043 protected static final String PROVIDER_RESOURCE = "META-INF/log4j-provider.properties"; 044 045 /** 046 * Loaded providers. 047 */ 048 protected static final Collection<Provider> PROVIDERS = new HashSet<>(); 049 050 /** 051 * Guards the ProviderUtil singleton instance from lazy initialization. This is primarily used for OSGi support. 052 * 053 * @since 2.1 054 */ 055 protected static final Lock STARTUP_LOCK = new ReentrantLock(); 056 057 private static final String API_VERSION = "Log4jAPIVersion"; 058 private static final String[] COMPATIBLE_API_VERSIONS = {"2.6.0"}; 059 private static final Logger LOGGER = StatusLogger.getLogger(); 060 061 // STARTUP_LOCK guards INSTANCE for lazy initialization; this allows the OSGi Activator to pause the startup and 062 // wait for a Provider to be installed. See LOG4J2-373 063 private static volatile ProviderUtil instance; 064 065 private ProviderUtil() { 066 for (ClassLoader classLoader : LoaderUtil.getClassLoaders()) { 067 try { 068 loadProviders(classLoader); 069 } catch (Throwable ex) { 070 LOGGER.debug("Unable to retrieve provider from ClassLoader {}", classLoader, ex); 071 } 072 } 073 for (final LoaderUtil.UrlResource resource : LoaderUtil.findUrlResources(PROVIDER_RESOURCE)) { 074 loadProvider(resource.getUrl(), resource.getClassLoader()); 075 } 076 } 077 078 protected static void addProvider(final Provider provider) { 079 PROVIDERS.add(provider); 080 LOGGER.debug("Loaded Provider {}", provider); 081 } 082 083 /** 084 * Loads an individual Provider implementation. This method is really only useful for the OSGi bundle activator and 085 * this class itself. 086 * 087 * @param url the URL to the provider properties file 088 * @param cl the ClassLoader to load the provider classes with 089 */ 090 protected static void loadProvider(final URL url, final ClassLoader cl) { 091 try { 092 final Properties props = PropertiesUtil.loadClose(url.openStream(), url); 093 if (validVersion(props.getProperty(API_VERSION))) { 094 final Provider provider = new Provider(props, url, cl); 095 PROVIDERS.add(provider); 096 LOGGER.debug("Loaded Provider {}", provider); 097 } 098 } catch (final IOException e) { 099 LOGGER.error("Unable to open {}", url, e); 100 } 101 } 102 103 protected static void loadProviders(final ClassLoader cl) { 104 final ServiceLoader<Provider> serviceLoader = ServiceLoader.load(Provider.class, cl); 105 for (final Provider provider : serviceLoader) { 106 if (validVersion(provider.getVersions()) && !PROVIDERS.contains(provider)) { 107 PROVIDERS.add(provider); 108 } 109 } 110 } 111 112 /** 113 * @deprecated Use {@link #loadProvider(java.net.URL, ClassLoader)} instead. Will be removed in 3.0. 114 */ 115 @Deprecated 116 protected static void loadProviders(final Enumeration<URL> urls, final ClassLoader cl) { 117 if (urls != null) { 118 while (urls.hasMoreElements()) { 119 loadProvider(urls.nextElement(), cl); 120 } 121 } 122 } 123 124 public static Iterable<Provider> getProviders() { 125 lazyInit(); 126 return PROVIDERS; 127 } 128 129 public static boolean hasProviders() { 130 lazyInit(); 131 return !PROVIDERS.isEmpty(); 132 } 133 134 /** 135 * Lazily initializes the ProviderUtil singleton. 136 * 137 * @since 2.1 138 */ 139 protected static void lazyInit() { 140 // noinspection DoubleCheckedLocking 141 if (instance == null) { 142 try { 143 STARTUP_LOCK.lockInterruptibly(); 144 try { 145 if (instance == null) { 146 instance = new ProviderUtil(); 147 } 148 } finally { 149 STARTUP_LOCK.unlock(); 150 } 151 } catch (final InterruptedException e) { 152 LOGGER.fatal("Interrupted before Log4j Providers could be loaded.", e); 153 Thread.currentThread().interrupt(); 154 } 155 } 156 } 157 158 public static ClassLoader findClassLoader() { 159 return LoaderUtil.getThreadContextClassLoader(); 160 } 161 162 private static boolean validVersion(final String version) { 163 for (final String v : COMPATIBLE_API_VERSIONS) { 164 if (version.startsWith(v)) { 165 return true; 166 } 167 } 168 return false; 169 } 170}