Java 类org.apache.logging.log4j.core.util.Loader 实例源码

项目:logging-log4j2    文件:MessagePatternConverter.java   
private TextRenderer loadMessageRenderer(final String[] options) {
    if (options != null) {
        for (final String option : options) {
            switch (option.toUpperCase(Locale.ROOT)) {
            case "ANSI":
                if (Loader.isJansiAvailable()) {
                    return new JAnsiTextRenderer(options, JAnsiTextRenderer.DefaultMessageStyleMap);
                }
                StatusLogger.getLogger()
                        .warn("You requested ANSI message rendering but JANSI is not on the classpath.");
                return null;
            case "HTML":
                return new HtmlTextRenderer(options);
            }
        }
    }
    return null;
}
项目:logging-log4j2    文件:ClockFactory.java   
private static Clock createClock() {
    final String userRequest = PropertiesUtil.getProperties().getStringProperty(PROPERTY_NAME);
    if (userRequest == null) {
        LOGGER.trace("Using default SystemClock for timestamps.");
        return logSupportedPrecision(new SystemClock());
    }
    Supplier<Clock> specified = aliases().get(userRequest);
    if (specified != null) {
        LOGGER.trace("Using specified {} for timestamps.", userRequest);
        return logSupportedPrecision(specified.get());
    }
    try {
        final Clock result = Loader.newCheckedInstanceOf(userRequest, Clock.class);
        LOGGER.trace("Using {} for timestamps.", result.getClass().getName());
        return logSupportedPrecision(result);
    } catch (final Exception e) {
        final String fmt = "Could not create {}: {}, using default SystemClock for timestamps.";
        LOGGER.error(fmt, userRequest, e);
        return logSupportedPrecision(new SystemClock());
    }
}
项目:logging-log4j2    文件:PluginRegistry.java   
/**
 * @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(Loader.getClassLoader());

    // 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();
}
项目:logging-log4j2    文件:OnStartupTriggeringPolicy.java   
/**
 * Returns the result of {@code ManagementFactory.getRuntimeMXBean().getStartTime()},
 * or the current system time if JMX is not available.
 */
private static long initStartTime() {
    // LOG4J2-379:
    // We'd like to call ManagementFactory.getRuntimeMXBean().getStartTime(),
    // but Google App Engine throws a java.lang.NoClassDefFoundError
    // "java.lang.management.ManagementFactory is a restricted class".
    // The reflection is necessary because without it, Google App Engine
    // will refuse to initialize this class.
    try {
        final Class<?> factoryClass = Loader.loadSystemClass("java.lang.management.ManagementFactory");
        final Method getRuntimeMXBean = factoryClass.getMethod("getRuntimeMXBean");
        final Object runtimeMXBean = getRuntimeMXBean.invoke(null);

        final Class<?> runtimeMXBeanClass = Loader.loadSystemClass("java.lang.management.RuntimeMXBean");
        final Method getStartTime = runtimeMXBeanClass.getMethod("getStartTime");
        final Long result = (Long) getStartTime.invoke(runtimeMXBean);

        return result;
    } catch (final Throwable t) {
        StatusLogger.getLogger().error("Unable to call ManagementFactory.getRuntimeMXBean().getStartTime(), "
                + "using system time for OnStartupTriggeringPolicy", t);
        // We have little option but to declare "now" as the beginning of time.
        return System.currentTimeMillis();
    }
}
项目:logging-log4j2    文件:PerfTest.java   
public void doMain(final String[] args) throws Exception {
    final String runnerClass = args[0];
    final IPerfTestRunner runner = Loader.newCheckedInstanceOf(runnerClass, IPerfTestRunner.class);
    final String name = args[1];
    final String resultFile = args.length > 2 ? args[2] : null;
    for (final String arg : args) {
        if (verbose && throughput) {
            break;
        }
        if ("-verbose".equalsIgnoreCase(arg)) {
            verbose = true;
        }
        if ("-throughput".equalsIgnoreCase(arg)) {
            throughput = true;
        }
    }
    final int threadCount = 1;
    printf("Starting %s %s (%d)...%n", getClass().getSimpleName(), name, threadCount);
    runTestAndPrintResult(runner, name, threadCount, resultFile);
    runner.shutdown();
    System.exit(0);
}
项目:monarch    文件:ConfigLocator.java   
/**
 * 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;
}
项目:logging-log4j2    文件:YamlConfigurationFactory.java   
public YamlConfigurationFactory() {
    for (final String dependency : dependencies) {
        if (!Loader.isClassAvailable(dependency)) {
            LOGGER.debug("Missing dependencies for Yaml support, ConfigurationFactory {} is inactive", getClass().getName());
            isActive = false;
            return;
        }
    }
    isActive = true;
}
项目:logging-log4j2    文件:ConfigurationSource.java   
/**
 * Retrieves the configuration via the ClassLoader.
 * @param resource The resource to load.
 * @param loader The default ClassLoader to use.
 * @return The ConfigurationSource for the configuration.
 */
public static ConfigurationSource fromResource(final String resource, final ClassLoader loader) {
    final URL url = Loader.getResource(resource, loader);
    if (url == null) {
        return null;
    }
    InputStream is = null;
    try {
        is = url.openStream();
    } catch (final IOException ioe) {
        ConfigurationFactory.LOGGER.catching(Level.DEBUG, ioe);
        return null;
    }
    if (is == null) {
        return null;
    }

    if (FileUtils.isFile(url)) {
        try {
            return new ConfigurationSource(is, FileUtils.fileFromUri(url.toURI()));
        } catch (final URISyntaxException ex) {
            // Just ignore the exception.
            ConfigurationFactory.LOGGER.catching(Level.DEBUG, ex);
        }
    }
    return new ConfigurationSource(is, url);
}
项目:logging-log4j2    文件:JsonConfigurationFactory.java   
public JsonConfigurationFactory() {
    for (final String dependency : dependencies) {
        if (!Loader.isClassAvailable(dependency)) {
            LOGGER.debug("Missing dependencies for Json support, ConfigurationFactory {} is inactive", getClass().getName());
            isActive = false;
            return;
        }
    }
    isActive = true;
}
项目:logging-log4j2    文件:ThrowableProxy.java   
private Class<?> loadClass(final String className) {
    try {
        return Loader.loadClass(className, this.getClass().getClassLoader());
    } catch (final ClassNotFoundException | NoClassDefFoundError | SecurityException e) {
        return null;
    }
}
项目:logging-log4j2    文件:PluginRegistry.java   
/**
 * @since 2.1
 */
public Map<String, List<PluginType<?>>> loadFromPackage(final String pkg) {
    if (Strings.isBlank(pkg)) {
        // happens when splitting an empty string
        return Collections.emptyMap();
    }
    Map<String, List<PluginType<?>>> existing = pluginsByCategoryByPackage.get(pkg);
    if (existing != null) {
        // already loaded this package
        return existing;
    }

    final long startTime = System.nanoTime();
    final ResolverUtil resolver = new ResolverUtil();
    final ClassLoader classLoader = Loader.getClassLoader();
    if (classLoader != null) {
        resolver.setClassLoader(classLoader);
    }
    resolver.findInPackage(new PluginTest(), pkg);

    final Map<String, List<PluginType<?>>> newPluginsByCategory = new HashMap<>();
    for (final Class<?> clazz : resolver.getClasses()) {
        final Plugin plugin = clazz.getAnnotation(Plugin.class);
        final String categoryLowerCase = plugin.category().toLowerCase();
        List<PluginType<?>> list = newPluginsByCategory.get(categoryLowerCase);
        if (list == null) {
            newPluginsByCategory.put(categoryLowerCase, list = new ArrayList<>());
        }
        final PluginEntry mainEntry = new PluginEntry();
        final String mainElementName = plugin.elementType().equals(
            Plugin.EMPTY) ? plugin.name() : plugin.elementType();
        mainEntry.setKey(plugin.name().toLowerCase());
        mainEntry.setName(plugin.name());
        mainEntry.setCategory(plugin.category());
        mainEntry.setClassName(clazz.getName());
        mainEntry.setPrintable(plugin.printObject());
        mainEntry.setDefer(plugin.deferChildren());
        final PluginType<?> mainType = new PluginType<>(mainEntry, clazz, mainElementName);
        list.add(mainType);
        final PluginAliases pluginAliases = clazz.getAnnotation(PluginAliases.class);
        if (pluginAliases != null) {
            for (final String alias : pluginAliases.value()) {
                final PluginEntry aliasEntry = new PluginEntry();
                final String aliasElementName = plugin.elementType().equals(
                    Plugin.EMPTY) ? alias.trim() : plugin.elementType();
                aliasEntry.setKey(alias.trim().toLowerCase());
                aliasEntry.setName(plugin.name());
                aliasEntry.setCategory(plugin.category());
                aliasEntry.setClassName(clazz.getName());
                aliasEntry.setPrintable(plugin.printObject());
                aliasEntry.setDefer(plugin.deferChildren());
                final PluginType<?> aliasType = new PluginType<>(aliasEntry, clazz, aliasElementName);
                list.add(aliasType);
            }
        }
    }

    final long endTime = System.nanoTime();
    final DecimalFormat numFormat = new DecimalFormat("#0.000000");
    final double seconds = (endTime - startTime) * 1e-9;
    LOGGER.debug("Took {} seconds to load {} plugins from package {}",
        numFormat.format(seconds), resolver.getClasses().size(), pkg);

    // 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 outer map.
    // Return the inner map produced by whichever thread won the race, so all callers will get the same result.
    existing = pluginsByCategoryByPackage.putIfAbsent(pkg, newPluginsByCategory);
    if (existing != null) {
        return existing;
    }
    return newPluginsByCategory;
}
项目:logging-log4j2    文件:ResponseTimeTest.java   
public static void main(final String[] args) throws Exception {
    if (args.length < 2) {
        System.out.println("Please specify thread count, target throughput (msg/sec) " +
                "and logger library (Log4j1, Log4j2, Logback, JUL)");
        return;
    }
    final int threadCount = Integer.parseInt(args[0]);
    final double loadMessagesPerSec = Double.parseDouble(args[1]);
    final String loggerLib = args.length > 2 ? args[2] : "Log4j2";

    // print to console if ringbuffer is full
    System.setProperty("log4j2.AsyncQueueFullPolicy", PrintingAsyncQueueFullPolicy.class.getName());
    System.setProperty("AsyncLogger.RingBufferSize", String.valueOf(256 * 1024));
    //System.setProperty("Log4jContextSelector", AsyncLoggerContextSelector.class.getName());
    //System.setProperty("log4j.configurationFile", "perf3PlainNoLoc.xml");
    if (System.getProperty("AsyncLogger.WaitStrategy") == null) {
        System.setProperty("AsyncLogger.WaitStrategy", "Yield");
    }
    //for (Object key : System.getProperties().keySet()) {
    //    System.out.println(key + "=" + System.getProperty((String) key));
    //}

    // initialize the logger
    final String wrapper = loggerLib.startsWith("Run") ? loggerLib : "Run" + loggerLib;
    final String loggerWrapperClass = "org.apache.logging.log4j.core.async.perftest." + wrapper;
    final IPerfTestRunner logger = Loader.newCheckedInstanceOf(loggerWrapperClass, IPerfTestRunner.class);
    logger.log("Starting..."); // ensure initialized
    Thread.sleep(100);

    final int requiredProcessors = threadCount + 1 + 1; // producers + 1 consumer + 1 for OS
    final IdleStrategy idleStrategy = Runtime.getRuntime().availableProcessors() > requiredProcessors
            ? new NoOpIdleStrategy()
            : new YieldIdleStrategy();

    System.out.printf("%s: %d threads, load is %,f msg/sec, using %s%n", loggerLib, threadCount,
            loadMessagesPerSec, idleStrategy.getClass().getSimpleName());

    // Warmup: run as many iterations of 50,000 calls to logger.log as we can in 1 minute
    final long WARMUP_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(1);
    final List<Histogram> warmupServiceTmHistograms = new ArrayList<>(threadCount);
    final List<Histogram> warmupResponseTmHistograms = new ArrayList<>(threadCount);

    final int WARMUP_COUNT = 50000 / threadCount;
    runLatencyTest(logger, WARMUP_DURATION_MILLIS, WARMUP_COUNT, loadMessagesPerSec, idleStrategy,
            warmupServiceTmHistograms, warmupResponseTmHistograms, threadCount);
    System.out.println("-----------------Warmup done. load=" + loadMessagesPerSec);
    if (!Constants.ENABLE_DIRECT_ENCODERS || !Constants.ENABLE_THREADLOCALS) {
        //System.gc();
        //Thread.sleep(5000);
    }
    System.out.println("-----------------Starting measured run. load=" + loadMessagesPerSec);

    final long start = System.currentTimeMillis();
    final List<Histogram> serviceTmHistograms = new ArrayList<>(threadCount);
    final List<Histogram> responseTmHistograms = new ArrayList<>(threadCount);
    PrintingAsyncQueueFullPolicy.ringbufferFull.set(0);

    // Actual test: run as many iterations of 1,000,000 calls to logger.log as we can in 4 minutes.
    final long TEST_DURATION_MILLIS = TimeUnit.MINUTES.toMillis(4);
    final int COUNT = (1000 * 1000) / threadCount;
    runLatencyTest(logger, TEST_DURATION_MILLIS, COUNT, loadMessagesPerSec, idleStrategy, serviceTmHistograms,
            responseTmHistograms, threadCount);
    logger.shutdown();
    final long end = System.currentTimeMillis();

    // ... and report the results
    final Histogram resultServiceTm = createResultHistogram(serviceTmHistograms, start, end);
    resultServiceTm.outputPercentileDistribution(System.out, 1000.0);
    writeToFile("s", resultServiceTm, (int) (loadMessagesPerSec / 1000), 1000.0);

    final Histogram resultResponseTm = createResultHistogram(responseTmHistograms, start, end);
    resultResponseTm.outputPercentileDistribution(System.out, 1000.0);
    writeToFile("r", resultResponseTm, (int) (loadMessagesPerSec / 1000), 1000.0);

    System.out.printf("%n%s: %d threads, load %,f msg/sec, ringbuffer full=%d%n", loggerLib, threadCount,
            loadMessagesPerSec, PrintingAsyncQueueFullPolicy.ringbufferFull.get());
    System.out.println("Test duration: " + (end - start) / 1000.0 + " seconds");
}
项目:logging-log4j2    文件:ResolverUtil.java   
/**
 * Returns the ClassLoader that will be used for scanning for classes. If no explicit ClassLoader has been set by
 * the calling, the context class loader will be used.
 *
 * @return the ClassLoader that will be used to scan for classes
 */
public ClassLoader getClassLoader() {
    return classloader != null ? classloader : (classloader = Loader.getClassLoader(ResolverUtil.class, null));
}