Example usage for java.util.logging LogManager getLogManager

List of usage examples for java.util.logging LogManager getLogManager

Introduction

In this page you can find the example usage for java.util.logging LogManager getLogManager.

Prototype

public static LogManager getLogManager() 

Source Link

Document

Returns the global LogManager object.

Usage

From source file:org.javaan.JavaanCli.java

private void setLoggerLevel(Level level) {
    Logger logger = LogManager.getLogManager().getLogger("");
    Handler[] handlers = logger.getHandlers();
    for (Handler handler : handlers) {
        handler.setLevel(level);/*from   www .  j a v a  2  s . c  om*/
    }
    logger.setLevel(level);
}

From source file:org.springframework.boot.context.logging.LoggingApplicationListenerTests.java

@Before
public void init() throws SecurityException, IOException {
    LogManager.getLogManager()
            .readConfiguration(JavaLoggingSystem.class.getResourceAsStream("logging.properties"));
    multicastEvent(new ApplicationStartingEvent(new SpringApplication(), NO_ARGS));
    new File("target/foo.log").delete();
    new File(tmpDir() + "/spring.log").delete();
    ConfigurableEnvironment environment = this.context.getEnvironment();
    ConfigurationPropertySources.attach(environment);
}

From source file:JCurl.java

protected LoggerContext initLogging() throws IOException {
    LogManager.getLogManager().reset();
    LogManager.getLogManager().readConfiguration();
    LogManager.getLogManager().getLogger("").setLevel(java.util.logging.Level.INFO);

    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();/*w w w . j a va 2s . co  m*/
    BasicConfigurator configurator = new BasicConfigurator();
    configurator.setContext(context);
    configurator.configure(context);
    context.getLogger(Logger.ROOT_LOGGER_NAME).setLevel(Level.INFO);
    org.slf4j.bridge.SLF4JBridgeHandler.removeHandlersForRootLogger();
    org.slf4j.bridge.SLF4JBridgeHandler.install();
    return context;
}

From source file:org.freaknet.gtrends.client.GoogleTrendsClientFactory.java

private static void setLogLevel(CmdLineParser cmdLine) throws SecurityException, IllegalArgumentException {
    final Level level;
    if (cmdLine.getLogLevel() != null) {
        level = Level.parse(cmdLine.getLogLevel());
    } else {/*from  ww  w  . j  ava  2 s  .  c  o m*/
        level = Level.parse(DEFAULT_LOGGING_LEVEL);
    }
    Logger log = LogManager.getLogManager().getLogger("");

    for (Handler h : log.getHandlers()) {
        log.removeHandler(h);
    }
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new LogFormatter());
    handler.setLevel(level);
    log.setUseParentHandlers(false);

    Logger defaultLog = Logger.getLogger(GoogleConfigurator.getLoggerPrefix());
    defaultLog.addHandler(handler);
    defaultLog.setLevel(level);
    defaultLog.setFilter(new Filter() {
        @Override
        public boolean isLoggable(LogRecord record) {
            if (record.getSourceClassName().startsWith(GoogleConfigurator.getLoggerPrefix())) {
                return (record.getLevel().intValue() >= level.intValue());
            }
            return false;
        }
    });
}

From source file:net.yacy.crawler.data.CacheTest.java

/**
 * Run a stress test on the Cache/*from w  ww .j  av  a2 s .com*/
 * 
 * @param args
 *            main arguments
 * @throws IOException
 *             when a error occurred
 */
public static void main(final String args[]) throws IOException {
    System.out.println("Stress test on Cache");

    /*
     * Set the root log level to WARNING to prevent filling the console with
     * too many information log messages
     */
    LogManager.getLogManager().readConfiguration(
            new ByteArrayInputStream(".level=WARNING".getBytes(StandardCharsets.ISO_8859_1)));

    /* Main control parameters. Modify values for different scenarios. */

    /* Number of concurrent test tasks */
    final int threads = 50;
    /* Number of steps in each task */
    final int steps = 10;
    /* Number of test URLs in each task */
    final int urlsPerThread = 5;
    /* Size of the generated test content */
    final int contentSize = Math.max(Cache.DEFAULT_COMPRESSOR_BUFFER_SIZE + 1,
            Cache.DEFAULT_BACKEND_BUFFER_SIZE + 1) / urlsPerThread;
    /* Cache maximum size */
    final long cacheMaxSize = Math.min(1024 * 1024 * 1024, ((long) contentSize) * 10 * urlsPerThread);
    /* Sleep time between each cache operation */
    final long sleepTime = 0;
    /* Maximum waiting time (in ms) for acquiring a synchronization lock */
    final long lockTimeout = 2000;
    /* The backend compression level */
    final int compressionLevel = Deflater.BEST_COMPRESSION;

    Cache.init(new File(System.getProperty("java.io.tmpdir") + File.separator + "yacyTestCache"), "peerSalt",
            cacheMaxSize, lockTimeout, compressionLevel);
    Cache.clear();
    System.out.println("Cache initialized with a maximum size of " + cacheMaxSize + " bytes.");

    try {
        System.out.println("Starting " + threads + " threads ...");
        long time = System.nanoTime();
        List<CacheAccessTask> tasks = new ArrayList<>();
        for (int count = 0; count < threads; count++) {
            List<DigestURL> urls = new ArrayList<>();
            for (int i = 0; i < urlsPerThread; i++) {
                urls.add(new DigestURL("http://yacy.net/" + i + "/" + count));
            }
            CacheAccessTask thread = new CacheAccessTask(urls, steps, contentSize, sleepTime);
            thread.start();
            tasks.add(thread);
        }
        /* Wait for tasks termination */
        for (CacheAccessTask task : tasks) {
            try {
                task.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /*
         * Check consistency : cache should be empty when all tasks have
         * terminated without error
         */
        Cache.commit();
        long docCount = Cache.getActualCacheDocCount();
        if (docCount > 0) {
            System.out.println("Cache is not empty!!! Actual documents count : " + docCount);
        }

        System.out.println("All threads terminated in "
                + TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - time) + "s. Computing statistics...");
        long storeTime = 0;
        long maxStoreTime = 0;
        long getContentTime = 0;
        long maxGetContentTime = 0;
        int storeFailures = 0;
        long deleteTime = 0;
        long maxDeleteTime = 0;
        long totalSteps = 0;
        for (CacheAccessTask task : tasks) {
            storeTime += task.getStoreTime();
            maxStoreTime = Math.max(task.getMaxStoreTime(), maxStoreTime);
            getContentTime += task.getGetContentTime();
            maxGetContentTime = Math.max(task.getMaxGetContentTime(), maxGetContentTime);
            storeFailures += task.getStoreFailures();
            deleteTime += task.getDeleteTime();
            maxDeleteTime = Math.max(task.getMaxDeleteTime(), maxDeleteTime);
            totalSteps += task.getSteps();
        }
        System.out.println("Cache.store() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime));
        System.out.println("Cache.store() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxStoreTime));
        System.out.println(
                "Cache.store() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(storeTime / totalSteps));
        System.out.println("Cache.store() failures : " + storeFailures);
        System.out.println("");
        System.out.println(
                "Cache.getContent() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(getContentTime));
        System.out.println(
                "Cache.getContent() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxGetContentTime));
        System.out.println("Cache.getContent() mean time (ms) : "
                + TimeUnit.NANOSECONDS.toMillis(getContentTime / totalSteps));
        System.out.println("Cache hits : " + Cache.getHits() + " total requests : " + Cache.getTotalRequests()
                + " ( hit rate : " + NumberFormat.getPercentInstance().format(Cache.getHitRate()) + " )");
        System.out.println("");
        System.out.println("Cache.delete() total time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime));
        System.out
                .println("Cache.delete() maximum time (ms) : " + TimeUnit.NANOSECONDS.toMillis(maxDeleteTime));
        System.out.println(
                "Cache.delete() mean time (ms) : " + TimeUnit.NANOSECONDS.toMillis(deleteTime / totalSteps));
    } finally {
        try {
            Cache.close();
        } finally {
            /* Shutdown running threads */
            ArrayStack.shutdownDeleteService();
            try {
                Domains.close();
            } finally {
                ConcurrentLog.shutdown();
            }
        }
    }

}

From source file:de.javakaffee.web.msm.integration.TestUtils.java

private static void initLogConfig(final Class<? extends TestUtils> clazz) {
    final URL loggingProperties = clazz.getResource("/logging.properties");
    try {//from  ww  w  .  ja v a 2  s . c  o  m
        System.setProperty("java.util.logging.config.file",
                new File(loggingProperties.toURI()).getAbsolutePath());
    } catch (final Exception e) {
        // we don't have a plain file (e.g. the case for msm-kryo-serializer etc), so we can skip reading the config
        return;
    }
    try {
        LogManager.getLogManager().readConfiguration();
    } catch (final Exception e) {
        LogFactory.getLog(TestUtils.class).error("Could not init logging configuration.", e);
    }
}

From source file:org.springframework.boot.logging.log4j.Log4JLoggingSystemTests.java

private boolean bridgeHandlerInstalled() {
    java.util.logging.Logger rootLogger = LogManager.getLogManager().getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
        if (handler instanceof SLF4JBridgeHandler) {
            return true;
        }//w w w. j  av  a  2 s .c om
    }
    return false;
}

From source file:org.motechproject.server.ws.RegistrarServiceTest.java

@AfterClass
public static void tearDownClass() throws Exception {
    ctx = null;/*  ww  w .  j  a  va 2s  .  c o  m*/
    regWs = null;
    registrarBean = null;
    openmrsBean = null;
    patientModelConverter = null;
    careModelConverter = null;
    LogManager.getLogManager().readConfiguration();
}

From source file:com.netspective.medigy.model.TestCase.java

protected HibernateConfiguration getHibernateConfiguration()
        throws HibernateException, FileNotFoundException, IOException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final Properties logProperties = new Properties();
    logProperties.setProperty("handlers", "java.util.logging.ConsoleHandler");
    logProperties.setProperty("java.util.logging.ConsoleHandler.formatter",
            "java.util.logging.SimpleFormatter");
    logProperties.setProperty("org.hibernate.level", "WARNING");
    logProperties.store(out, "Generated by " + TestCase.class.getName());
    LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(out.toByteArray()));

    final HibernateConfiguration config = new HibernateConfiguration();

    final Properties hibProperties = new Properties();
    hibProperties.setProperty(Environment.DIALECT, HSQLDialect.class.getName());
    hibProperties.setProperty(Environment.CONNECTION_PREFIX + ".driver_class", "org.hsqldb.jdbcDriver");
    hibProperties.setProperty(Environment.CONNECTION_PREFIX + ".url",
            "jdbc:hsqldb:" + databaseDirectory + "/db");
    hibProperties.setProperty(Environment.CONNECTION_PREFIX + ".username", "sa");
    hibProperties.setProperty(Environment.CONNECTION_PREFIX + ".password", "");
    hibProperties.setProperty(Environment.HBM2DDL_AUTO, "create-drop");
    hibProperties.setProperty(Environment.SHOW_SQL, "false");
    config.addProperties(hibProperties);

    for (final Class c : com.netspective.medigy.reference.Catalog.ALL_REFERENCE_TYPES)
        config.addAnnotatedClass(c);//  w w  w  . j a  v a  2  s .c  o m

    try {
        config.configure("com/netspective/medigy/hibernate.cfg.xml");
    } catch (HibernateException e) {
        log.error(e);
        throw new RuntimeException(e);
    }
    config.registerReferenceEntitiesAndCaches();
    return config;
}

From source file:org.lilyproject.lilyservertestfw.launcher.LilyLauncher.java

@Override
public int run(CommandLine cmd) throws Exception {
    int result = super.run(cmd);
    if (result != 0) {
        return result;
    }/*from  w w  w  .j  av  a2s.  c o m*/

    // Forward JDK logging to SLF4J
    LogManager.getLogManager().reset();
    LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler());
    LogManager.getLogManager().getLogger("").setLevel(Level.ALL);

    boolean prepareMode = cmd.hasOption(prepareOption.getOpt());

    //
    // Figure out what to start
    //
    enableHadoop = cmd.hasOption(enableHadoopOption.getOpt());
    enableSolr = cmd.hasOption(enableSolrOption.getOpt());
    enableLily = cmd.hasOption(enableLilyOption.getOpt());
    enableHbaseIndexer = cmd.hasOption(enableHbaseIndexerOption.getOpt());

    // When running prepare mode, or if none of the services are explicitly enabled,
    // we default to starting them all. Otherwise we only start those that are enabled.
    if (!enableHadoop && !enableSolr && !enableLily && !enableHbaseIndexer) {
        enableHadoop = true;
        enableSolr = true;
        enableLily = true;
        enableHbaseIndexer = true;
    }

    if (prepareMode) {
        // (in prepare mode: always start everything)
        System.out.println("-------------------------------------------------------------");
        System.out.println("Running in prepare mode (ignoring --hadoop, --lily, --solr).");
        System.out.println("Will start up, stop, and then snapshot the data directory.");
        System.out.println("Please be patient.");
        System.out.println("-------------------------------------------------------------");

        // If there would be an old template dir, drop it
        TemplateDir.deleteTemplateDir();
    }

    if (enableHadoop) {
        enabledServices.add(hadoopService);
    }
    if (enableSolr) {
        enabledServices.add(solrService);
    }
    if (enableLily) {
        enabledServices.add(lilyService);
    }
    if (enableHbaseIndexer) {
        enabledServices.add(hbaseIndexerLauncherService);
    }

    //
    // Determine directory below which all services will store their data
    //
    if (!prepareMode && cmd.hasOption(dataDirOption.getOpt())) {
        String dataDir = cmd.getOptionValue(dataDirOption.getOpt());
        testHome = new File(dataDir);
        if (testHome.exists() && !testHome.isDirectory()) {
            System.err.println("Specified data directory exists and is not a directory:");
            System.err.println(testHome.getAbsolutePath());
            return -1;
        } else if (testHome.exists() && testHome.isDirectory() && testHome.list().length > 0) {
            System.out.println("Specified data directory exists: will re-use data from previous run!");
        } else if (!testHome.exists()) {
            FileUtils.forceMkdir(testHome);
        }
        // If the user specified the storage directory, do not delete it
        clearData = false;
    } else {
        testHome = TestHomeUtil.createTestHome("lily-launcher-");
        if (!prepareMode) {
            TemplateDir.restoreTemplateDir(testHome);
        }
    }

    //
    // Start the services
    //

    // Informational messages to be outputted after startup has completed.
    List<String> postStartupInfo = new ArrayList<String>();

    for (LauncherService service : enabledServices) {
        if ((result = service.setup(cmd, testHome, clearData)) != 0) {
            return result;
        }
    }

    for (LauncherService service : enabledServices) {
        if ((result = service.start(postStartupInfo)) != 0) {
            return result;
        }
    }

    if (prepareMode) {
        System.out.println("----------------------------------------------------------");
        System.out.println("Prepare mode: stopping all services");
        System.out.println("----------------------------------------------------------");
        lilyService.stop();
        solrService.stop();
        hadoopService.stop();

        System.out.println("----------------------------------------------------------");
        System.out.println("Prepare mode: creating template data directory");
        TemplateDir.makeTemplateDir(testHome);
        System.out.println("----------------------------------------------------------");
        System.out.println("Done");

        System.exit(0);
    }

    // Register MBean
    ManagementFactory.getPlatformMBeanServer().registerMBean(this,
            new ObjectName("LilyLauncher:name=Launcher"));

    // Add shutdown hook
    Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownHook()));

    //
    // Finished startup, print messages
    //
    for (String msg : postStartupInfo) {
        System.out.println(msg);
    }

    // redirect all jdk logging (e.g. from Restlet) to log4j (done after startup of all services, to make sure
    // all loggers registered during startup of some services are also redirected)
    JavaLoggingToLog4jRedirector.activate();

    return 0;
}