下面列出了怎么用org.apache.logging.log4j.util.LoaderUtil的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Class<?> convert(final String s) throws ClassNotFoundException {
switch (s.toLowerCase()) {
case "boolean":
return boolean.class;
case "byte":
return byte.class;
case "char":
return char.class;
case "double":
return double.class;
case "float":
return float.class;
case "int":
return int.class;
case "long":
return long.class;
case "short":
return short.class;
case "void":
return void.class;
default:
return LoaderUtil.loadClass(s);
}
}
/**
* Retrieve plugins from the main classloader.
* @return Map of the List of PluginTypes by category.
* @since 2.1
*/
public Map<String, List<PluginType<?>>> loadFromMainClassLoader() {
final Map<String, List<PluginType<?>>> existing = pluginsByCategoryRef.get();
if (existing != null) {
// already loaded
return existing;
}
final Map<String, List<PluginType<?>>> newPluginsByCategory = decodeCacheFiles(LoaderUtil.getClassLoader());
loadPlugins(newPluginsByCategory);
// Note multiple threads could be calling this method concurrently. Both will do the work,
// but only one will be allowed to store the result in the AtomicReference.
// Return the map produced by whichever thread won the race, so all callers will get the same result.
if (pluginsByCategoryRef.compareAndSet(null, newPluginsByCategory)) {
return newPluginsByCategory;
}
return pluginsByCategoryRef.get();
}
/**
* Instantiate an object given a class name. Check that the
* <code>className</code> is a subclass of
* <code>superClass</code>. If that test fails or the object could
* not be instantiated, then <code>defaultValue</code> is returned.
*
* @param className The fully qualified class name of the object to instantiate.
* @param superClass The class to which the new object should belong.
* @param defaultValue The object to return in case of non-fulfillment
* @return The created object.
*/
public static Object instantiateByClassName(String className, Class<?> superClass,
Object defaultValue) {
if (className != null) {
try {
Object obj = LoaderUtil.newInstanceOf(className);
if (!superClass.isAssignableFrom(obj.getClass())) {
LOGGER.error("A \"{}\" object is not assignable to a \"{}\" variable", className,
superClass.getName());
return defaultValue;
}
return obj;
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
| InstantiationException | InvocationTargetException e) {
LOGGER.error("Could not instantiate class [" + className + "].", e);
}
}
return defaultValue;
}
private RewritePolicy buildRewritePolicy(String className, Element element) {
try {
RewritePolicy policy = LoaderUtil.newInstanceOf(className);
PropertySetter propSetter = new PropertySetter(policy);
forEachElement(element.getChildNodes(), (currentElement) -> {
if (currentElement.getTagName().equalsIgnoreCase(PARAM_TAG)) {
setParameter(currentElement, propSetter);
}
});
propSetter.activate();
return policy;
} catch (ConsumerException ex) {
Throwable t = ex.getCause();
if (t instanceof InterruptedException || t instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LOGGER.error("Could not create an RewritePolicy. Reported error follows.", t);
} catch (Exception oops) {
if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LOGGER.error("Could not create an RewritePolicy. Reported error follows.", oops);
}
return null;
}
private <T extends AbstractBuilder> T createBuilder(PluginType<?> plugin, String prefix, Properties props) {
try {
Class<?> clazz = plugin.getPluginClass();
if (AbstractBuilder.class.isAssignableFrom(clazz)) {
@SuppressWarnings("unchecked")
Constructor<T> constructor =
(Constructor<T>) clazz.getConstructor(constructorParams);
return constructor.newInstance(prefix, props);
} else {
@SuppressWarnings("unchecked")
T builder = (T) LoaderUtil.newInstanceOf(clazz);
return builder;
}
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
return null;
}
}
/**
* Instantiate an object given a class name. Check that the
* <code>className</code> is a subclass of
* <code>superClass</code>. If that test fails or the object could
* not be instantiated, then <code>defaultValue</code> is returned.
*
* @param className The fully qualified class name of the object to instantiate.
* @param superClass The class to which the new object should belong.
* @param defaultValue The object to return in case of non-fulfillment
*/
public static Object instantiateByClassName(String className, Class<?> superClass,
Object defaultValue) {
if (className != null) {
try {
Object obj = LoaderUtil.newInstanceOf(className);
if (!superClass.isAssignableFrom(obj.getClass())) {
LOGGER.error("A \"{}\" object is not assignable to a \"{}\" variable", className,
superClass.getName());
return defaultValue;
}
return obj;
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
| InstantiationException | InvocationTargetException e) {
LOGGER.error("Could not instantiate class [" + className + "].", e);
}
}
return defaultValue;
}
public static AuthorizationProvider authorizationProvider(PropertiesUtil props) {
final String authClass = props.getStringProperty(AUTHORIZATION_PROVIDER);
AuthorizationProvider provider = null;
if (authClass != null) {
try {
Object obj = LoaderUtil.newInstanceOf(authClass);
if (obj instanceof AuthorizationProvider) {
provider = (AuthorizationProvider) obj;
} else {
LOGGER.warn("{} is not an AuthorizationProvider, using default", obj.getClass().getName());
}
} catch (Exception ex) {
LOGGER.warn("Unable to create {}, using default: {}", authClass, ex.getMessage());
}
}
if (provider == null) {
provider = new BasicAuthorizationProvider(props);
}
return provider;
}
public BasicAuthorizationProvider(PropertiesUtil props) {
String userName = props.getStringProperty(PREFIXES,AUTH_USER_NAME,
() -> props.getStringProperty(CONFIG_USER_NAME));
String password = props.getStringProperty(PREFIXES, AUTH_PASSWORD,
() -> props.getStringProperty(CONFIG_PASSWORD));
String decryptor = props.getStringProperty(PREFIXES, AUTH_PASSWORD_DECRYPTOR,
() -> props.getStringProperty(PASSWORD_DECRYPTOR));
if (decryptor != null) {
try {
Object obj = LoaderUtil.newInstanceOf(decryptor);
if (obj instanceof PasswordDecryptor) {
password = ((PasswordDecryptor) obj).decryptPassword(password);
}
} catch (Exception ex) {
LOGGER.warn("Unable to decrypt password.", ex);
}
}
if (userName != null && password != null) {
authString = "Basic " + encoder.encodeToString((userName + ":" + password).getBytes());
}
}
private Class loadClass(String className, String argName) {
if (className == null) {
throw new ConfigurationException(String.format("No %s provided for %s", argName, JacksonMixIn.PLUGIN_NAME));
}
try {
return LoaderUtil.loadClass(className);
} catch (ClassNotFoundException e) {
throw new ConfigurationException(String.format("Cannot load %s: %s for %s", argName, className, JacksonMixIn.PLUGIN_NAME));
}
}
public ClassPathCatalogReader(Map<String, String> attributes) throws IOException {
String catalogFile = attributes != null ?
attributes.getOrDefault(CATALOG_ATTRIBUTE_NAME, DEFAULT_CATALOG_FILE) : DEFAULT_CATALOG_FILE;
Collection<URL> catalogs = LoaderUtil.findResources(catalogFile);
if (catalogs.isEmpty()) {
LOGGER.error("No catalog named {} could be found on the class path", catalogFile);
throw new FileNotFoundException("No catalog named " + catalogFile + " could be found");
}
URL catalogURL = catalogs.iterator().next();
if (catalogs.size() > 1) {
LOGGER.warn("Multiple catalogs named {} were found. Using {}", catalogFile, catalogURL.toString());
}
catalog = readCatalog(catalogURL);
LocalDateTime localDateTime = null;
try {
URLConnection connection = catalogURL.openConnection();
localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(connection.getLastModified()),
ZoneId.systemDefault());
} catch (IOException ioe) {
LOGGER.warn("Unable to open connection to {}", catalogURL.toString());
}
lastUpdated = localDateTime;
JsonFactory factory = new JsonFactory();
factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
ObjectMapper objectMapper = new ObjectMapper(factory);
catalogData = objectMapper.readValue(catalog, CatalogData.class);
}
/**
* Gets the {@link LoggerContext} associated with the given caller class.
*
* @param callerClass the caller class
* @return the LoggerContext for the calling class
*/
protected LoggerContext getContext(final Class<?> callerClass) {
ClassLoader cl = null;
if (callerClass != null) {
cl = callerClass.getClassLoader();
}
if (cl == null) {
cl = LoaderUtil.getThreadContextClassLoader();
}
return LogManager.getContext(cl, false);
}
private static Class<? extends MessageFactory> createClassForProperty(final String property,
final Class<ReusableMessageFactory> reusableParameterizedMessageFactoryClass,
final Class<ParameterizedMessageFactory> parameterizedMessageFactoryClass) {
try {
final String fallback = Constants.ENABLE_THREADLOCALS ? reusableParameterizedMessageFactoryClass.getName()
: parameterizedMessageFactoryClass.getName();
final String clsName = PropertiesUtil.getProperties().getStringProperty(property, fallback);
return LoaderUtil.loadClass(clsName).asSubclass(MessageFactory.class);
} catch (final Throwable t) {
return parameterizedMessageFactoryClass;
}
}
private static Class<? extends FlowMessageFactory> createFlowClassForProperty(final String property,
final Class<DefaultFlowMessageFactory> defaultFlowMessageFactoryClass) {
try {
final String clsName = PropertiesUtil.getProperties().getStringProperty(property, defaultFlowMessageFactoryClass.getName());
return LoaderUtil.loadClass(clsName).asSubclass(FlowMessageFactory.class);
} catch (final Throwable t) {
return defaultFlowMessageFactoryClass;
}
}
/**
* Load plugins across all ClassLoaders.
* @param map The Map of the lists of plugins organized by category.
* @since 3.0
*/
public void loadPlugins(Map<String, List<PluginType<?>>> map) {
for (ClassLoader classLoader : LoaderUtil.getClassLoaders()) {
try {
loadPlugins(classLoader, map);
} catch (Throwable ex) {
LOGGER.debug("Unable to retrieve provider from ClassLoader {}", classLoader, ex);
}
}
}
private Layout buildLayout(String className, Element layout_element) {
try {
Layout layout = LoaderUtil.newInstanceOf(className);
PropertySetter propSetter = new PropertySetter(layout);
forEachElement(layout_element.getChildNodes(), (currentElement) -> {
String tagName = currentElement.getTagName();
if (tagName.equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
} else {
try {
parseUnrecognizedElement(layout, currentElement, props);
} catch (Exception ex) {
throw new ConsumerException(ex);
}
}
});
propSetter.activate();
return layout;
} catch (ConsumerException ce) {
Throwable cause = ce.getCause();
if (cause instanceof InterruptedException || cause instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LOGGER.error("Could not create the Layout. Reported error follows.", cause);
} catch (Exception oops) {
if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LOGGER.error("Could not create the Layout. Reported error follows.", oops);
}
return null;
}
/**
* Used internally to parse a level element.
*/
private void parseLevel(Element element, LoggerConfig logger, boolean isRoot) {
String catName = logger.getName();
if (isRoot) {
catName = "root";
}
String priStr = subst(element.getAttribute(VALUE_ATTR));
LOGGER.debug("Level value for {} is [{}}].", catName, priStr);
if (INHERITED.equalsIgnoreCase(priStr) || NULL.equalsIgnoreCase(priStr)) {
if (isRoot) {
LOGGER.error("Root level cannot be inherited. Ignoring directive.");
} else {
logger.setLevel(null);
}
} else {
String className = subst(element.getAttribute(CLASS_ATTR));
if (EMPTY_STR.equals(className)) {
logger.setLevel(OptionConverter.convertLevel(priStr, org.apache.logging.log4j.Level.DEBUG));
} else {
LOGGER.debug("Desired Level sub-class: [{}]", className);
try {
Class<?> clazz = LoaderUtil.loadClass(className);
Method toLevelMethod = clazz.getMethod("toLevel", ONE_STRING_PARAM);
Level pri = (Level) toLevelMethod.invoke(null, new Object[]{priStr});
logger.setLevel(OptionConverter.convertLevel(pri));
} catch (Exception oops) {
if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LOGGER.error("Could not create level [" + priStr +
"]. Reported error follows.", oops);
return;
}
}
}
LOGGER.debug("{} level set to {}", catName, logger.getLevel());
}
private static <T> T newInstanceOf(String className, String type) {
try {
return LoaderUtil.newInstanceOf(className);
} catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException |
InstantiationException | InvocationTargetException ex) {
LOGGER.error("Unable to create {} {} due to {}:{}", type, className,
ex.getClass().getSimpleName(), ex.getMessage());
return null;
}
}
public Appender parseAppender(String className, Element appenderElement, XmlConfiguration config) {
PluginType<?> plugin = plugins.get(className.toLowerCase());
if (plugin != null) {
try {
@SuppressWarnings("unchecked")
AppenderBuilder builder = (AppenderBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
return builder.parseAppender(appenderElement, config);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
}
}
return null;
}
public Filter parseFilter(String className, Element filterElement, XmlConfiguration config) {
PluginType<?> plugin = plugins.get(className.toLowerCase());
if (plugin != null) {
try {
@SuppressWarnings("unchecked")
FilterBuilder builder = (FilterBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
return builder.parseFilter(filterElement, config);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
}
}
return null;
}
public Layout parseLayout(String className, Element layoutElement, XmlConfiguration config) {
PluginType<?> plugin = plugins.get(className.toLowerCase());
if (plugin != null) {
try {
@SuppressWarnings("unchecked")
LayoutBuilder builder = (LayoutBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
return builder.parseLayout(layoutElement, config);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
}
}
return null;
}
public RewritePolicy parseRewritePolicy(String className, Element rewriteElement, XmlConfiguration config) {
PluginType<?> plugin = plugins.get(className.toLowerCase());
if (plugin != null) {
try {
@SuppressWarnings("unchecked")
RewritePolicyBuilder builder = (RewritePolicyBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
return builder.parseRewritePolicy(rewriteElement, config);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
}
}
return null;
}
private Layout buildLayout(String className, Element layout_element) {
try {
Layout layout = LoaderUtil.newInstanceOf(className);
PropertySetter propSetter = new PropertySetter(layout);
forEachElement(layout_element.getChildNodes(), (currentElement) -> {
String tagName = currentElement.getTagName();
if (tagName.equals(PARAM_TAG)) {
setParameter(currentElement, propSetter);
} else {
try {
parseUnrecognizedElement(layout, currentElement, props);
} catch (Exception ex) {
throw new ConsumerException(ex);
}
}
});
propSetter.activate();
return layout;
} catch (ConsumerException ce) {
Throwable cause = ce.getCause();
if (cause instanceof InterruptedException || cause instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LOGGER.error("Could not create the Layout. Reported error follows.", cause);
} catch (Exception oops) {
if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LOGGER.error("Could not create the Layout. Reported error follows.", oops);
}
return null;
}
/**
* Used internally to parse a level element.
*/
private void parseLevel(Element element, LoggerConfig logger, boolean isRoot) {
String catName = logger.getName();
if (isRoot) {
catName = "root";
}
String priStr = subst(element.getAttribute(VALUE_ATTR));
LOGGER.debug("Level value for {} is [{}}].", catName, priStr);
if (INHERITED.equalsIgnoreCase(priStr) || NULL.equalsIgnoreCase(priStr)) {
if (isRoot) {
LOGGER.error("Root level cannot be inherited. Ignoring directive.");
} else {
logger.setLevel(null);
}
} else {
String className = subst(element.getAttribute(CLASS_ATTR));
if (EMPTY_STR.equals(className)) {
logger.setLevel(convertLevel(OptionConverter.toLevel(priStr, Level.DEBUG)));
} else {
LOGGER.debug("Desired Level sub-class: [{}]", className);
try {
Class<?> clazz = LoaderUtil.loadClass(className);
Method toLevelMethod = clazz.getMethod("toLevel", ONE_STRING_PARAM);
Level pri = (Level) toLevelMethod.invoke(null, new Object[]{priStr});
logger.setLevel(convertLevel(pri));
} catch (Exception oops) {
if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LOGGER.error("Could not create level [" + priStr +
"]. Reported error follows.", oops);
return;
}
}
}
LOGGER.debug("{} level set to {}", catName, logger.getLevel());
}
public Appender parseAppender(String className, Element appenderElement, XmlConfigurationFactory factory) {
PluginType<?> plugin = plugins.get(className.toLowerCase());
if (plugin != null) {
try {
@SuppressWarnings("unchecked")
AppenderBuilder builder = (AppenderBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
return builder.parseAppender(appenderElement, factory);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
}
}
return null;
}
public Filter parseFilter(String className, Element filterElement, XmlConfigurationFactory factory) {
PluginType<?> plugin = plugins.get(className.toLowerCase());
if (plugin != null) {
try {
@SuppressWarnings("unchecked")
FilterBuilder builder = (FilterBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
return builder.parseFilter(filterElement, factory);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
}
}
return null;
}
public Layout parseLayout(String className, Element layoutElement, XmlConfigurationFactory factory) {
PluginType<?> plugin = plugins.get(className.toLowerCase());
if (plugin != null) {
try {
@SuppressWarnings("unchecked")
LayoutBuilder builder = (LayoutBuilder) LoaderUtil.newInstanceOf(plugin.getPluginClass());
return builder.parseLayout(layoutElement, factory);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException ex) {
LOGGER.warn("Unable to load plugin: {} due to: {}", plugin.getKey(), ex.getMessage());
}
}
return null;
}
private static EventDataConverter createConverter() {
try {
LoaderUtil.loadClass("org.slf4j.ext.EventData");
return new EventDataConverter();
} catch (final ClassNotFoundException cnfe) {
return null;
}
}
private ClassLoader getClassLoader() {
try {
// if container is Servlet 3.0, use its getClassLoader method
// this may look odd, but the call below will throw NoSuchMethodError if user is on Servlet 2.5
// we compile against 3.0 to support Log4jServletContainerInitializer, but we don't require 3.0
return this.servletContext.getClassLoader();
} catch (final Throwable ignore) {
// LOG4J2-248: use TCCL if possible
return LoaderUtil.getThreadContextClassLoader();
}
}
public SLF4JLoggerContextFactory() {
// LOG4J2-230, LOG4J2-204 (improve error reporting when misconfigured)
boolean misconfigured = false;
try {
LoaderUtil.loadClass("org.slf4j.helpers.Log4jLoggerFactory");
misconfigured = true;
} catch (final ClassNotFoundException classNotFoundIsGood) {
LOGGER.debug("org.slf4j.helpers.Log4jLoggerFactory is not on classpath. Good!");
}
if (misconfigured) {
throw new IllegalStateException("slf4j-impl jar is mutually exclusive with log4j-to-slf4j jar "
+ "(the first routes calls from SLF4J to Log4j, the second from Log4j to SLF4J)");
}
}
private Configuration getConfiguration(String requiredVersion, final LoggerContext loggerContext,
final String configLocationStr) {
ConfigurationSource source = null;
try {
source = ConfigurationSource.fromUri(NetUtils.toURI(configLocationStr));
} catch (final Exception ex) {
// Ignore the error and try as a String.
LOGGER.catching(Level.DEBUG, ex);
}
if (source == null) {
final ClassLoader loader = LoaderUtil.getThreadContextClassLoader();
source = getInputFromString(configLocationStr, loader);
}
if (source != null) {
for (final ConfigurationFactory factory : getFactories()) {
if (requiredVersion != null && !factory.getVersion().equals(requiredVersion)) {
continue;
}
final String[] types = factory.getSupportedTypes();
if (types != null) {
for (final String type : types) {
if (type.equals(ALL_TYPES) || configLocationStr.endsWith(type)) {
final Configuration config = factory.getConfiguration(loggerContext, source);
if (config != null) {
return config;
}
}
}
}
}
}
return null;
}