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.uma.jmetal.util.JMetalLogger.java

/**
 * This method provides a single-call method to configure the {@link Logger}
 * instances. A default configuration is considered, enriched with a custom
 * property file for more convenient logging. The custom file is considered
 * after the default configuration, so it can override it if necessary. The
 * custom file might be provided as an argument of this method, otherwise we
 * look for a file named "jMetal.log.ini". If no custom file is provided,
 * then only the default configuration is considered.
 * // w  w  w .  j a va  2s  .c  o  m
 * @param propertyFile
 *            the property file to use for custom configuration,
 *            <code>null</code> to use only the default configuration
 * @throws IOException
 */
public static void configureLoggers(File propertyFile) throws IOException {
    // Prepare default configuration
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    PrintStream printer = new PrintStream(stream);
    printer.println(".level = INFO");
    printer.println("handlers = java.util.logging.FileHandler, java.util.logging.ConsoleHandler");
    printer.println("formatters = java.util.logging.SimpleFormatter");
    printer.println(
            "java.util.logging.SimpleFormatter.format = %1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS.%1$tL %4$s: %5$s [%2$s]%6$s%n");

    printer.println("java.util.logging.FileHandler.pattern = jMetal.log");
    printer.println("java.util.logging.FileHandler.level = ALL");

    printer.println("java.util.logging.ConsoleHandler.level = ALL");

    // Retrieve custom configuration
    File defaultFile = new File("jMetal.log.ini");
    if (propertyFile != null) {
        printer.println(FileUtils.readFileToString(propertyFile));
    } else if (defaultFile.exists()) {
        printer.println(FileUtils.readFileToString(defaultFile));
    } else {
        // use only default configuration
    }
    printer.close();

    // Apply configuration
    LogManager manager = LogManager.getLogManager();
    manager.readConfiguration(
            IOUtils.toInputStream(new String(stream.toByteArray(), Charset.forName("UTF-8"))));
    logger.info("Loggers configured with " + propertyFile);
}

From source file:org.tros.utils.logging.Logging.java

public static void initLogging(BuildInfo binfo, Class init) {
    try {//  w w  w  .j  ava2  s.c o  m
        //hack to get this logger to shut up
        Class<?> forName = Class.forName("org.reflections.Reflections");
        Field f = forName.getField("log");
        f.set(null, null);
    } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException
            | IllegalAccessException ex) {
        Logger.getLogger(Logging.class.getName()).log(Level.FINEST,
                "org.reflections.Reflections not in CLASSPATH...");
    }

    //make logs directory
    getLogDirectory(binfo);

    //init logger
    String dir = getApplicationEtcDirectory(binfo) + "/logging.properties";
    File logProp = new File(dir);
    if (!logProp.exists()) {
        copyFile(binfo, init, logProp);
    }

    if (logProp.exists()) {
        loadFile(logProp);
    }

    LogManager lm = LogManager.getLogManager();
    String property = lm.getProperty("version");
    if (property == null || !property.equals(binfo.getVersion().replace("-SNAPSHOT", ""))) {
        //backup old file
        File backup = new File(logProp.getAbsolutePath() + "." + (property == null ? "old" : property));
        logProp.renameTo(backup);
        //copy new file
        copyFile(binfo, init, logProp);
        //re-load new file
        loadFile(logProp);
    }

    //Small hack to close SwingComponentHandler which should only be used by a GUI
    //however, if the logging.properties file is already set with this handler, remove
    //it and then the GUI will manually re-add it in the LogConsole constructor.
    Logger logger = Logger.getLogger("");
    try {
        Class<?> swingLogger = Class.forName("org.tros.utils.logging.SwingComponentHandler");
        for (Handler h : logger.getHandlers()) {
            if (swingLogger.isAssignableFrom(h.getClass())) {
                logger.removeHandler(h);
                h.close();
            }
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Logging.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.fhg.iais.asc.ui.MyCortexStarter.java

private static void configureLogging() {
    String hostAddress = "n/a";
    try {//from   ww  w. j a  v a  2s.c  om
        hostAddress = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        LOG.warn("Hostname/IP not available");
    }
    MDC.put("host_name", hostAddress);

    // SLF4J is bound to logback
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure("conf/logback.xml");
    } catch (JoranException je) {
        je.printStackTrace(); // NOSONAR
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);

    LOG.info("-- CORTEX starting");

    java.util.logging.Logger rootLogger = LogManager.getLogManager().getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
        rootLogger.removeHandler(handler);
    }
    SLF4JBridgeHandler.install();
}

From source file:ffx.Main.java

/**
 * Replace the default console handler with our custom FFX handler.
 *///from w  w  w  .  j  a va2 s  .c o m
private static void startLogging() {
    // Remove all log handlers from the default logger.
    try {
        Logger defaultLogger = LogManager.getLogManager().getLogger("");
        Handler defaultHandlers[] = defaultLogger.getHandlers();
        for (Handler h : defaultHandlers) {
            defaultLogger.removeHandler(h);
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }

    // Retrieve the log level from the ffx.log system property.
    String logLevel = System.getProperty("ffx.log", "info");
    Level tempLevel;
    try {
        tempLevel = Level.parse(logLevel.toUpperCase());
    } catch (Exception e) {
        tempLevel = Level.INFO;
    }

    level = tempLevel;
    logHandler = new LogHandler();
    logHandler.setLevel(level);
    Logger ffxLogger = Logger.getLogger("ffx");
    ffxLogger.addHandler(logHandler);
    ffxLogger.setLevel(level);
}

From source file:edu.usu.sdl.openstorefront.web.action.admin.LoggingAction.java

@HandlesEvent("UpdateHandlerLevel")
public Resolution updateHandlerLevel() {
    Logger localLogger = LogManager.getLogManager().getLogger(logger);
    if (localLogger != null) {

        for (Handler handlerLocal : localLogger.getHandlers()) {
            if (handlerLocal.getClass().getName().equals(handler)) {
                if (StringUtils.isNotBlank(level)) {
                    handlerLocal.setLevel(Level.parse(level));
                } else {
                    handlerLocal.setLevel(null);
                }//w  w  w. ja  v a2 s. c o m
            }
        }
        log.log(Level.INFO, SecurityUtil.adminAuditLogMessage(getContext().getRequest()));
    } else {
        throw new OpenStorefrontRuntimeException("Unable to find logger", "Check name");
    }

    return viewLoggers();
}

From source file:org.xwiki.rest.internal.XWikiRestletServlet.java

@Override
public void init() throws ServletException {
    super.init();

    try {/*from   w  w w.j av a2 s  . c o m*/
        /* Try first in WEB-INF */
        InputStream is = getServletContext()
                .getResourceAsStream(String.format("/WEB-INF/%s", JAVA_LOGGING_PROPERTY_FILE));

        /* If nothing is there then try in the current jar */
        if (is == null) {
            is = getClass().getClassLoader().getResourceAsStream(JAVA_LOGGING_PROPERTY_FILE);
        }

        if (is != null) {
            try {
                LogManager.getLogManager().readConfiguration(is);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    } catch (Exception e) {
        log("Unable to initialize Java logging framework. Using defaults", e);
    }
}

From source file:org.wattdepot.server.WattDepotServer.java

/**
 * Creates a new instance of the WattDepot server.
 * /*from  w w  w  .  j a  v a  2  s  .  c o m*/
 * @param properties
 *          The ServerProperties used to initialize this server.
 * @return The WattDepotServer.
 * @throws Exception
 *           if there is a problem starting the server.
 */
public static WattDepotServer newInstance(ServerProperties properties) throws Exception {
    int port = Integer.parseInt(properties.get(ServerProperties.PORT_KEY));
    WattDepotServer server = new WattDepotServer();
    // System.out.println("WattDepotServer.");
    //    LoggerUtil.showLoggers();
    boolean enableLogging = Boolean.parseBoolean(properties.get(ServerProperties.ENABLE_LOGGING_KEY));
    server.serverProperties = properties;
    server.hostName = server.serverProperties.getFullHost();

    // Get the WattDepotPersistence implementation.
    String depotClass = properties.get(ServerProperties.WATT_DEPOT_IMPL_KEY);
    server.depot = (WattDepotPersistence) Class.forName(depotClass).getConstructor(ServerProperties.class)
            .newInstance(properties);
    if (server.depot.getSessionOpen() != server.depot.getSessionClose()) {
        throw new RuntimeException("opens and closed mismatched.");
    }
    server.depot.initializeMeasurementTypes();
    if (server.depot.getSessionOpen() != server.depot.getSessionClose()) {
        throw new RuntimeException("opens and closed mismatched.");
    }
    server.depot.initializeSensorModels();
    if (server.depot.getSessionOpen() != server.depot.getSessionClose()) {
        throw new RuntimeException("opens and closed mismatched.");
    }
    server.depot.setServerProperties(properties);
    server.restletServer = new WattDepotComponent(server.depot, port);
    server.logger = server.restletServer.getLogger();

    // Set up logging.
    if (enableLogging) {
        LoggerUtil.useConsoleHandler();
        Logger base = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        base = base.getParent();
        String level = properties.get(ServerProperties.LOGGING_LEVEL_KEY);
        LoggerUtil.setLoggingLevel(base, level);

        server.logger.info("Starting WattDepot server.");
        server.logger.info("Host: " + server.hostName);
        server.logger.info(server.serverProperties.echoProperties());
    } else {
        LoggerUtil.useConsoleHandler();
        Logger base = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
        base = base.getParent();
        LoggerUtil.setLoggingLevel(base, Level.SEVERE.toString());
    }
    server.restletServer.start();

    server.logger.info("WattDepot server now running.");

    //    LoggerUtil.showLoggers();
    return server;
}

From source file:com.github.apetrelli.scafa.ScafaLauncher.java

public void launch(String profile) {
    File home = new File(System.getProperty("user.home"));
    File scafaDirectory = new File(home, ".scafa");
    ensureConfigDirectoryPresent(scafaDirectory);
    try (InputStream stream = new FileInputStream(new File(scafaDirectory, "logging.properties"))) {
        LogManager.getLogManager().readConfiguration(stream);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Cannot load logging configuration, exiting", e);
        System.exit(1);//from   w  ww .j a  v  a  2 s .c o  m
    }
    try {
        Configuration configuration = Configuration.create(profile);
        Integer port = configuration.getMainConfiguration().get("port", int.class);
        proxy = new ScafaListener<>(
                new DefaultProcessorFactory<>(new ProxyHttpByteSinkFactory(),
                        new ProxyBufferProcessorFactory<>(), HttpStatus.IDLE),
                new ProxyHttpHandlerFactory(new DefaultHttpConnectionFactoryFactory(configuration)), port);
        proxy.listen();
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Cannot start proxy", e);
    }
}

From source file:net.openhft.chronicle.logger.jul.JulTestBase.java

/**
 *
 * @param id/*ww w  .  j a  v a 2s  .  c  om*/
 * @throws IOException
 */
protected void setupLogManager(String id) throws IOException {
    String cfgPath = System.getProperty("resources.path");
    File cfgFile = new File(cfgPath, id + ".properties");

    assertNotNull(cfgPath);
    assertTrue(cfgFile.exists());

    LogManager manager = LogManager.getLogManager();
    manager.reset();
    manager.readConfiguration(new FileInputStream(cfgFile));
}

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

@BeforeClass
public static void setUpClass() throws Exception {
    LogManager.getLogManager()
            .readConfiguration(RegistrarServiceTest.class.getResourceAsStream("/jul-test.properties"));
    registrarBean = createMock(RegistrarBean.class);
    openmrsBean = createMock(OpenmrsBean.class);
    patientModelConverter = createMock(WebServicePatientModelConverter.class);
    careModelConverter = createMock(WebServiceCareModelConverter.class);
    ctx = new ClassPathXmlApplicationContext("test-context.xml");

    RegistrarWebService regService = (RegistrarWebService) ctx.getBean("registrarService");
    regService.setRegistrarBean(registrarBean);
    regService.setOpenmrsBean(openmrsBean);
    regService.setPatientModelConverter(patientModelConverter);
    regService.setCareModelConverter(careModelConverter);

    regWs = (RegistrarService) ctx.getBean("registrarClient");
}