org.apache.logging.log4j.util.LoaderUtil Java Examples

The following examples show how to use org.apache.logging.log4j.util.LoaderUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OptionConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: OptionConverter.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example #4
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: ConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: PluginRegistry.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #7
Source File: TypeConverters.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@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);
    }

}
 
Example #8
Source File: BasicAuthorizationProvider.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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());
    }
}
 
Example #9
Source File: ConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Configuration getConfiguration(final LoggerContext loggerContext, final boolean isTest, final String name) {
    final boolean named = Strings.isNotEmpty(name);
    final ClassLoader loader = LoaderUtil.getThreadContextClassLoader();
    for (final ConfigurationFactory factory : getFactories()) {
        String configName;
        final String prefix = isTest ? factory.getTestPrefix() : factory.getDefaultPrefix();
        final String [] types = factory.getSupportedTypes();
        if (types == null) {
            continue;
        }

        for (final String suffix : types) {
            if (suffix.equals(ALL_TYPES)) {
                continue;
            }
            configName = named ? prefix + name + suffix : prefix + suffix;

            final ConfigurationSource source = ConfigurationSource.fromResource(configName, loader);
            if (source != null) {
                if (!factory.isActive()) {
                    LOGGER.warn("Found configuration file {} for inactive ConfigurationFactory {}", configName, factory.getClass().getName());
                }
                return factory.getConfiguration(loggerContext, source);
            }
        }
    }
    return null;
}
 
Example #10
Source File: ConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #11
Source File: SLF4JLoggerContextFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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)");
    }
}
 
Example #12
Source File: ClassPathCatalogReader.java    From logging-log4j-audit with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #13
Source File: WatchManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private List<WatchEventService> getEventServices() {
    List<WatchEventService> list = new ArrayList<>();
    for (final ClassLoader classLoader : LoaderUtil.getClassLoaders()) {
        try {
            final ServiceLoader<WatchEventService> serviceLoader =
                    ServiceLoader.load(WatchEventService.class, classLoader);
            for (final WatchEventService service : serviceLoader) {
                list.add(service);
            }
        } catch (final Throwable ex) {
            LOGGER.debug("Unable to retrieve WatchEventService from ClassLoader {}", classLoader, ex);
        }
    }
    return list;
}
 
Example #14
Source File: Log4jWebInitializerImpl.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example #15
Source File: Log4jLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static EventDataConverter createConverter() {
    try {
        LoaderUtil.loadClass("org.slf4j.ext.EventData");
        return new EventDataConverter();
    } catch (final ClassNotFoundException cnfe) {
        return null;
    }
}
 
Example #16
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #17
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #18
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #19
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example #20
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #21
Source File: Loader.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if a named Class can be loaded or not.
 *
 * @param className The class name.
 * @return {@code true} if the class could be found or {@code false} otherwise.
 */
public static boolean isClassAvailable(final String className) {
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(getClassLoader());
        return LoaderUtil.isClassAvailable(className);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}
 
Example #22
Source File: ThreadContextDataInjector.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static List<ContextDataProvider> getServiceProviders() {
    List<ContextDataProvider> providers = new ArrayList<>();
    for (final ClassLoader classLoader : LoaderUtil.getClassLoaders()) {
        try {
            for (final ContextDataProvider provider : ServiceLoader.load(ContextDataProvider.class, classLoader)) {
                if (providers.stream().noneMatch((p) -> p.getClass().isAssignableFrom(provider.getClass()))) {
                    providers.add(provider);
                }
            }
        } catch (final Throwable ex) {
            LOGGER.debug("Unable to access Context Data Providers {}", ex.getMessage());
        }
    }
    return providers;
}
 
Example #23
Source File: BuilderManager.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #24
Source File: JacksonMixIn.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
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));
            }

        }
 
Example #25
Source File: AbstractLoggerAdapter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #26
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #27
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example #28
Source File: PluginRegistry.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #29
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #30
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}