/** * Returns a new {@code ReliabilityStrategy} instance based on the value of system property * {@code log4j.ReliabilityStrategy}. If not value was specified this method returns a new * {@code AwaitUnconditionallyReliabilityStrategy}. * <p> * Valid values for this system property are {@code "AwaitUnconditionally"} (use * {@code AwaitUnconditionallyReliabilityStrategy}), {@code "Locking"} (use {@code LockingReliabilityStrategy}) and * {@code "AwaitCompletion"} (use the default {@code AwaitCompletionReliabilityStrategy}). * <p> * Users may also use this system property to specify the fully qualified class name of a class that implements the * {@code ReliabilityStrategy} and has a constructor that accepts a single {@code LoggerConfig} argument. * * @param loggerConfig the LoggerConfig the resulting {@code ReliabilityStrategy} is associated with * @return a ReliabilityStrategy that helps the specified LoggerConfig to log events reliably during or after a * configuration change */ public static ReliabilityStrategy getReliabilityStrategy(final LoggerConfig loggerConfig) { final String strategy = PropertiesUtil.getProperties().getStringProperty("log4j.ReliabilityStrategy", "AwaitCompletion"); if ("AwaitCompletion".equals(strategy)) { return new AwaitCompletionReliabilityStrategy(loggerConfig); } if ("AwaitUnconditionally".equals(strategy)) { return new AwaitUnconditionallyReliabilityStrategy(loggerConfig); } if ("Locking".equals(strategy)) { return new LockingReliabilityStrategy(loggerConfig); } try { final Class<? extends ReliabilityStrategy> cls = LoaderUtil.loadClass(strategy).asSubclass( ReliabilityStrategy.class); return cls.getConstructor(LoggerConfig.class).newInstance(loggerConfig); } catch (final Exception dynamicFailed) { StatusLogger.getLogger().warn( "Could not create ReliabilityStrategy for '{}', using default AwaitCompletionReliabilityStrategy: {}", strategy, dynamicFailed); return new AwaitCompletionReliabilityStrategy(loggerConfig); } }
@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); } }
/** * 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(final String className, final Class<?> superClass, final Object defaultValue) { if (className != null) { try { final Class<?> classObj = LoaderUtil.loadClass(className); if (!superClass.isAssignableFrom(classObj)) { LOGGER.error("A \"{}\" object is not assignable to a \"{}\" variable.", className, superClass.getName()); LOGGER.error("The class \"{}\" was loaded by [{}] whereas object of type [{}] was loaded by [{}].", superClass.getName(), superClass.getClassLoader(), classObj.getName()); return defaultValue; } return classObj.newInstance(); } catch (final Exception e) { LOGGER.error("Could not instantiate class [{}].", className, e); } } return defaultValue; }
private static WriteConcern toWriteConcern(final String writeConcernConstant, final String writeConcernConstantClassName) { WriteConcern writeConcern; if (Strings.isNotEmpty(writeConcernConstant)) { if (Strings.isNotEmpty(writeConcernConstantClassName)) { try { final Class<?> writeConcernConstantClass = LoaderUtil.loadClass(writeConcernConstantClassName); final Field field = writeConcernConstantClass.getField(writeConcernConstant); writeConcern = (WriteConcern) field.get(null); } catch (final Exception e) { LOGGER.error("Write concern constant [{}.{}] not found, using default.", writeConcernConstantClassName, writeConcernConstant); writeConcern = DEFAULT_WRITE_CONCERN; } } else { writeConcern = WriteConcern.valueOf(writeConcernConstant); if (writeConcern == null) { LOGGER.warn("Write concern constant [{}] not found, using default.", writeConcernConstant); writeConcern = DEFAULT_WRITE_CONCERN; } } } else { writeConcern = DEFAULT_WRITE_CONCERN; } return writeConcern; }
/** * This should replicate the classpath search for configuration file that Log4J 2 performs. * Returns the configuration location as URI or null if none is found. * * @return configuration location or null if not found */ public static URL findConfigInClasspath() { final ClassLoader loader = LoaderUtil.getThreadContextClassLoader(); for (final String suffix : SUFFIXES) { String resource = PREFIX + suffix; URL url = Loader.getResource(resource, loader); if (url != null) { // found it return url; } } return null; }
/** * 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; } }
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)"); } }
/** * Construct the ComponsiteConfiguration. * * @param configurations The List of Configurations to merge. */ public CompositeConfiguration(final List<? extends AbstractConfiguration> configurations) { super(configurations.get(0).getLoggerContext(), ConfigurationSource.NULL_SOURCE); rootNode = configurations.get(0).getRootNode(); this.configurations = configurations; final String mergeStrategyClassName = PropertiesUtil.getProperties().getStringProperty(MERGE_STRATEGY_PROPERTY, DefaultMergeStrategy.class.getName()); try { mergeStrategy = LoaderUtil.newInstanceOf(mergeStrategyClassName); } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException ex) { mergeStrategy = new DefaultMergeStrategy(); } for (final AbstractConfiguration config : configurations) { mergeStrategy.mergeRootProperties(rootNode, config); } final StatusConfiguration statusConfig = new StatusConfiguration().withVerboseClasses(VERBOSE_CLASSES) .withStatus(getDefaultStatus()); for (final Map.Entry<String, String> entry : rootNode.getAttributes().entrySet()) { final String key = entry.getKey(); final String value = getStrSubstitutor().replace(entry.getValue()); if ("status".equalsIgnoreCase(key)) { statusConfig.withStatus(value.toUpperCase()); } else if ("dest".equalsIgnoreCase(key)) { statusConfig.withDestination(value); } else if ("shutdownHook".equalsIgnoreCase(key)) { isShutdownHookEnabled = !"disable".equalsIgnoreCase(value); } else if ("shutdownTimeout".equalsIgnoreCase(key)) { shutdownTimeoutMillis = Long.parseLong(value); } else if ("verbose".equalsIgnoreCase(key)) { statusConfig.withVerbosity(value); } else if ("packages".equalsIgnoreCase(key)) { pluginPackages.addAll(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR))); } else if ("name".equalsIgnoreCase(key)) { setName(value); } } statusConfig.initialize(); }
private static void addFactory(final Collection<ConfigurationFactory> list, final String factoryClass) { try { addFactory(list, LoaderUtil.loadClass(factoryClass).asSubclass(ConfigurationFactory.class)); } catch (final Exception ex) { LOGGER.error("Unable to load class {}", factoryClass, ex); } }
private Configuration getConfiguration(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()) { 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; }
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 ? TEST_PREFIX : DEFAULT_PREFIX; 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; }
private static Class<? extends StringMap> createCachedClass(final String className) { if (className == null) { return null; } try { return LoaderUtil.loadClass(className).asSubclass(IndexedStringMap.class); } catch (final Exception any) { return null; } }
private static ContextSelector createContextSelector() { try { final ContextSelector selector = LoaderUtil.newCheckedInstanceOfProperty(Constants.LOG4J_CONTEXT_SELECTOR, ContextSelector.class); if (selector != null) { return selector; } } catch (final Exception e) { LOGGER.error("Unable to create custom ContextSelector. Falling back to default.", e); } return new ClassLoaderContextSelector(); }
private static ShutdownCallbackRegistry createShutdownCallbackRegistry() { try { final ShutdownCallbackRegistry registry = LoaderUtil.newCheckedInstanceOfProperty( ShutdownCallbackRegistry.SHUTDOWN_CALLBACK_REGISTRY, ShutdownCallbackRegistry.class ); if (registry != null) { return registry; } } catch (final Exception e) { LOGGER.error("Unable to create custom ShutdownCallbackRegistry. Falling back to default.", e); } return new DefaultShutdownCallbackRegistry(); }
static ExceptionHandler<RingBufferLogEvent> getAsyncLoggerExceptionHandler() { final String cls = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.ExceptionHandler"); if (cls == null) { return new AsyncLoggerDefaultExceptionHandler(); } try { @SuppressWarnings("unchecked") final Class<? extends ExceptionHandler<RingBufferLogEvent>> klass = (Class<? extends ExceptionHandler<RingBufferLogEvent>>) LoaderUtil.loadClass(cls); return klass.newInstance(); } catch (final Exception ignored) { LOGGER.debug("Invalid AsyncLogger.ExceptionHandler value: error creating {}: ", cls, ignored); return new AsyncLoggerDefaultExceptionHandler(); } }
static ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper> getAsyncLoggerConfigExceptionHandler() { final String cls = PropertiesUtil.getProperties().getStringProperty("AsyncLoggerConfig.ExceptionHandler"); if (cls == null) { return new AsyncLoggerConfigDefaultExceptionHandler(); } try { @SuppressWarnings("unchecked") final Class<? extends ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper>> klass = (Class<? extends ExceptionHandler<AsyncLoggerConfigDisruptor.Log4jEventWrapper>>) LoaderUtil.loadClass(cls); return klass.newInstance(); } catch (final Exception ignored) { LOGGER.debug("Invalid AsyncLoggerConfig.ExceptionHandler value: error creating {}: ", cls, ignored); return new AsyncLoggerConfigDefaultExceptionHandler(); } }
private static AsyncQueueFullPolicy createCustomRouter(final String router) { try { final Class<? extends AsyncQueueFullPolicy> cls = LoaderUtil.loadClass(router).asSubclass(AsyncQueueFullPolicy.class); LOGGER.debug("Creating custom AsyncQueueFullPolicy '{}'", router); return cls.newInstance(); } catch (final Exception ex) { LOGGER.debug("Using DefaultAsyncQueueFullPolicy. Could not create custom AsyncQueueFullPolicy '{}': {}", router, ex.toString()); return new DefaultAsyncQueueFullPolicy(); } }
private Throwable getThrowable(final String throwableClassName, final String message, final Throwable cause, final StackTraceElement[] stackTrace) { try { @SuppressWarnings("unchecked") final Class<Throwable> throwableClass = (Class<Throwable>) LoaderUtil.loadClass(throwableClassName); if (!Throwable.class.isAssignableFrom(throwableClass)) { return null; } Throwable throwable; if (message != null && cause != null) { throwable = this.getThrowable(throwableClass, message, cause); if (throwable == null) { throwable = this.getThrowable(throwableClass, cause); if (throwable == null) { throwable = this.getThrowable(throwableClass, message); if (throwable == null) { throwable = this.getThrowable(throwableClass); if (throwable != null) { THROWABLE_MESSAGE.set(throwable, message); THROWABLE_CAUSE.set(throwable, cause); } } else { THROWABLE_CAUSE.set(throwable, cause); } } else { THROWABLE_MESSAGE.set(throwable, message); } } } else if (cause != null) { throwable = this.getThrowable(throwableClass, cause); if (throwable == null) { throwable = this.getThrowable(throwableClass); if (throwable != null) { THROWABLE_CAUSE.set(throwable, cause); } } } else if (message != null) { throwable = this.getThrowable(throwableClass, message); if (throwable == null) { throwable = this.getThrowable(throwableClass); if (throwable != null) { THROWABLE_MESSAGE.set(throwable, cause); } } } else { throwable = this.getThrowable(throwableClass); } if (throwable == null) { return null; } throwable.setStackTrace(stackTrace); return throwable; } catch (final Exception e) { return null; } }
/** * Returns a new {@code ContextDataInjector} instance based on the value of system property * {@code log4j2.ContextDataInjector}. If no value was specified this factory method returns one of the * {@code ContextDataInjector} classes defined in {@link ThreadContextDataInjector} which is most appropriate for * the ThreadContext implementation. * <p> * Users may use this system property to specify the fully qualified class name of a class that implements the * {@code ContextDataInjector} interface. * </p><p> * When providing a custom {@code ContextDataInjector}, be aware that this method may be invoked multiple times by * the various components in Log4j that need access to context data. * This includes the object(s) that populate log events, but also various lookups and filters that look at * context data to determine whether an event should be logged. * </p> * * @return a ContextDataInjector that populates the {@code ReadOnlyStringMap} of all {@code LogEvent} objects * @see LogEvent#getContextData() * @see ContextDataInjector */ public static ContextDataInjector createInjector() { final String className = PropertiesUtil.getProperties().getStringProperty("log4j2.ContextDataInjector"); if (className == null) { return createDefaultInjector(); } try { final Class<? extends ContextDataInjector> cls = LoaderUtil.loadClass(className).asSubclass( ContextDataInjector.class); return cls.newInstance(); } catch (final Exception dynamicFailed) { final ContextDataInjector result = createDefaultInjector(); StatusLogger.getLogger().warn( "Could not create ContextDataInjector for '{}', using default {}: {}", className, result.getClass().getName(), dynamicFailed); return result; } }
public TestClassLoader() { super(LoaderUtil.getThreadContextClassLoader()); }
/** * Loads and instantiates a Class using the default constructor. * * @param className The class name. * @return new instance of the class. * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders * @throws IllegalAccessException if the class can't be instantiated through a public constructor * @throws InstantiationException if there was an exception whilst instantiating the class * @throws NoSuchMethodException if there isn't a no-args constructor on the class * @throws InvocationTargetException if there was an exception whilst constructing the class */ public static Object newInstanceOf(final String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException { return LoaderUtil.newInstanceOf(className); }
/** * Loads, instantiates, and casts a Class using the default constructor. * * @param className The class name. * @param clazz The class to cast it to. * @param <T> The type to cast it to. * @return new instance of the class cast to {@code T} * @throws ClassNotFoundException if the class isn't available to the usual ClassLoaders * @throws IllegalAccessException if the class can't be instantiated through a public constructor * @throws InstantiationException if there was an exception whilst instantiating the class * @throws NoSuchMethodException if there isn't a no-args constructor on the class * @throws InvocationTargetException if there was an exception whilst constructing the class * @throws ClassCastException if the constructed object isn't type compatible with {@code T} */ public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { return LoaderUtil.newCheckedInstanceOf(className, clazz); }
/** * Returns the ClassLoader of current thread if possible, or falls back to the system ClassLoader if none is * available. * * @return the TCCL. * @see org.apache.logging.log4j.util.LoaderUtil#getThreadContextClassLoader() */ public static ClassLoader getThreadContextClassLoader() { return LoaderUtil.getThreadContextClassLoader(); }
/** * 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) { return LoaderUtil.isClassAvailable(className); }