Example usage for java.util.logging LogManager readConfiguration

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

Introduction

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

Prototype

public void readConfiguration(InputStream ins) throws IOException, SecurityException 

Source Link

Document

Reads and initializes the logging configuration from the given input stream.

Usage

From source file:com.bluemarsh.jswat.console.Main.java

/**
 * Kicks off the application./* ww  w  . ja va2 s .c o  m*/
 *
 * @param  args  the command line arguments.
 */
public static void main(String[] args) {
    //
    // An attempt was made early on to use the Console class in java.io,
    // but that is not designed to handle asynchronous output from
    // multiple threads, so we just use the usual System.out for output
    // and System.in for input. Note that automatic flushing is used to
    // ensure output is shown in a timely fashion.
    //

    //
    // Where console mode seems to work:
    // - bash
    // - emacs
    //
    // Where console mode does not seem to work:
    // - NetBeans: output from event listeners is never shown and the
    //   cursor sometimes lags behind the output
    //

    // Turn on flushing so printing the prompt will flush
    // all buffered output generated from other threads.
    PrintWriter output = new PrintWriter(System.out, true);

    // Make sure we have the JPDA classes.
    try {
        Bootstrap.virtualMachineManager();
    } catch (NoClassDefFoundError ncdfe) {
        output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA"));
        System.exit(1);
    }

    // Ensure we can create the user directory by requesting the
    // platform service. Simply asking for it has the desired effect.
    PlatformProvider.getPlatformService();

    // Define the logging configuration.
    LogManager manager = LogManager.getLogManager();
    InputStream is = Main.class.getResourceAsStream("logging.properties");
    try {
        manager.readConfiguration(is);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(1);
    }

    // Print out some useful debugging information.
    logSystemDetails();

    // Add a shutdown hook to make sure we exit cleanly.
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            // Save the command aliases.
            CommandParser parser = CommandProvider.getCommandParser();
            parser.saveSettings();
            // Save the runtimes to persistent storage.
            RuntimeManager rm = RuntimeProvider.getRuntimeManager();
            rm.saveRuntimes();
            // Save the sessions to persistent storage and have them
            // close down in preparation to exit.
            SessionManager sm = SessionProvider.getSessionManager();
            sm.saveSessions(true);
        }
    }));

    // Initialize the command parser and load the aliases.
    CommandParser parser = CommandProvider.getCommandParser();
    parser.loadSettings();
    parser.setOutput(output);

    // Create an OutputAdapter to display debuggee output.
    OutputAdapter adapter = new OutputAdapter(output);
    SessionManager sessionMgr = SessionProvider.getSessionManager();
    sessionMgr.addSessionManagerListener(adapter);
    // Create a SessionWatcher to monitor the session status.
    SessionWatcher swatcher = new SessionWatcher();
    sessionMgr.addSessionManagerListener(swatcher);
    // Create a BreakpointWatcher to monitor the breakpoints.
    BreakpointWatcher bwatcher = new BreakpointWatcher();
    sessionMgr.addSessionManagerListener(bwatcher);

    // Add the watchers and adapters to the open sessions.
    Iterator<Session> iter = sessionMgr.iterateSessions();
    while (iter.hasNext()) {
        Session s = iter.next();
        s.addSessionListener(adapter);
        s.addSessionListener(swatcher);
    }

    // Find and run the RC file.
    try {
        runStartupFile(parser, output);
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
    }

    // Process command line arguments.
    try {
        processArguments(args);
    } catch (ParseException pe) {
        // Report the problem and keep going.
        System.err.println("Option parsing failed: " + pe.getMessage());
        logger.log(Level.SEVERE, null, pe);
    }

    // Display a helpful greeting.
    output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome"));
    if (jdbEmulationMode) {
        output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation"));
    }

    // Enter the main loop of processing user input.
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    while (true) {
        // Keep the prompt format identical to jdb for compatibility
        // with emacs and other possible wrappers.
        output.print("> ");
        output.flush();
        try {
            String command = input.readLine();
            // A null value indicates end of stream.
            if (command != null) {
                performCommand(output, parser, command);
            }
            // Sleep briefly to give the event processing threads,
            // and the automatic output flushing, a chance to catch
            // up before printing the input prompt again.
            Thread.sleep(250);
        } catch (InterruptedException ie) {
            logger.log(Level.WARNING, null, ie);
        } catch (IOException ioe) {
            logger.log(Level.SEVERE, null, ioe);
            output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe));
        } catch (Exception x) {
            // Don't ever let an internal bug (e.g. in the command parser)
            // hork the console, as it really irritates people.
            logger.log(Level.SEVERE, null, x);
            output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x));
        }
    }
}

From source file:name.livitski.databag.cli.Launcher.java

public static void main(String[] args) {
    Launcher tool = new Launcher();
    LogManager logging = LogManager.getLogManager();
    Class<?> beanClass = tool.getClass();
    InputStream cfg = beanClass.getResourceAsStream("/logging.properties");
    try {//from  ww  w . ja  v a  2s.co m
        logging.readConfiguration(cfg);
    } catch (Exception e) {
        System.err.println("WARNING: could not initialize logging. Detailed diagnostics may not be available. "
                + e.getMessage());
    } finally {
        try {
            cfg.close();
            cfg = null;
        } catch (Exception ignored) {
        }
    }
    try {
        tool.setOptions(SYNTAX.parseCommandLine(args));
    } catch (ParseException e) {
        tool.log().severe(e.getMessage());
        showHelpHint();
        System.exit(Status.SYNTAX.getCode());
    }
    if (null != tool.getOptions())
        tool.run();
    if (Status.OK != tool.getStatus())
        System.exit(tool.getStatus().getCode());
}

From source file:de.otto.mongodb.profiler.web.util.LogManagerLifecycle.java

public void configure() throws IOException {
    final LogManager logManager = LogManager.getLogManager();
    logManager.readConfiguration(defaultConfig.getInputStream());
    logger.info("Logging has been configured.");
}

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

/**
 *
 * @param id/*  w  w  w  .ja  va  2 s  .  co  m*/
 * @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:com.izforge.izpack.util.LogUtils.java

public static void loadConfiguration(final Properties configuration) throws IOException {
    if (OVERRIDE) {
        LogManager manager = LogManager.getLogManager();

        // Merge global logging properties
        InputStream baseResourceStream = null;
        try {//from ww  w .  ja v  a2s  .c  o  m
            baseResourceStream = LogUtils.class.getResourceAsStream(LOGGING_BASE_CONFIGURATION);
            final Properties baseProps = new Properties();
            baseProps.load(baseResourceStream);
            mergeLoggingConfiguration(configuration, baseProps);
        } finally {
            IOUtils.closeQuietly(baseResourceStream);
        }

        boolean mkdirs = false;
        String pattern = null;
        if (configuration.getProperty("handlers") != null
                && configuration.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)
                && manager.getProperty("handlers").contains(FILEHANDLER_CLASSNAME)) {
            // IzPack maintains just one log file, don't override the existing handler type of it.
            // Special use case: Command line argument -logfile "wins" over the <log-file> tag.
            // Assumption at the moment for optimization: Just FileHandler is used for configurations from install.xml.
            return;
        }
        for (String key : configuration.stringPropertyNames()) {
            if (key.equals(FILEHANDLER_CLASSNAME + ".pattern")) {
                // Workaround for not normalized file paths, for example ${INSTALL_PATH}/../install_log/name.log
                // to get them working before creating ${INSTALL_PATH} in the
                // com.izforge.izpack.installer.unpacker.UnpackerBase.preUnpack phase
                // otherwise the FileHandler will fail when opening files already in constructor and not recover from that.
                pattern = FilenameUtils.normalize(configuration.getProperty(key));
                configuration.setProperty(key, pattern);
            } else if (key.equals(FILEHANDLER_CLASSNAME + ".mkdirs")) {
                // This key goes beyond the capabilities of java.util.logging.FileHandler
                mkdirs = Boolean.parseBoolean(configuration.getProperty(key));
                configuration.remove(key);
            }
        }
        if (mkdirs && pattern != null) {
            FileUtils.forceMkdirParent(new File(pattern));
        }

        // Merge user settings compiled in
        final Properties userProps = new Properties();
        InputStream userPropsStream = LogUtils.class
                .getResourceAsStream(ResourceManager.getInstallLoggingConfigurationResourceName());
        try {
            if (userPropsStream != null) {
                userProps.load(userPropsStream);
                for (String userPropName : userProps.stringPropertyNames()) {
                    if (userPropName.endsWith(".level") && !userPropName.startsWith(FILEHANDLER_CLASSNAME)) {
                        String level = userProps.getProperty(userPropName);
                        if (level != null) {
                            configuration.setProperty(userPropName, level);
                        }
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(userPropsStream);
        }

        InputStream defaultResourceStream = null;
        try {
            defaultResourceStream = LogUtils.class.getResourceAsStream(LOGGING_CONFIGURATION);
            final Properties defaultProps = new Properties();
            defaultProps.load(defaultResourceStream);
            mergeLoggingConfiguration(configuration, defaultProps);
        } finally {
            IOUtils.closeQuietly(defaultResourceStream);
        }

        if (Debug.isDEBUG()) {
            configuration.setProperty(FILEHANDLER_CLASSNAME + ".level", Level.FINE.toString());
            configuration.setProperty(ConsoleHandler.class.getName() + ".level", Level.FINE.toString());
        }

        // Set general log level which acts as filter in front of all handlers
        String fileLevelName = configuration.getProperty(FILEHANDLER_CLASSNAME + ".level",
                Level.ALL.toString());
        Level fileLevel = Level.ALL;
        if (fileLevelName != null) {
            fileLevel = Level.parse(fileLevelName);
        }

        String consoleLevelName = configuration.getProperty(CONSOLEHANDLER_CLASSNAME + ".level",
                Level.INFO.toString());
        Level consoleLevel = Level.INFO;
        if (consoleLevelName != null) {
            consoleLevel = Level.parse(consoleLevelName);
        }

        configuration.setProperty(".level",
                (fileLevel.intValue() < consoleLevel.intValue()) ? fileLevelName : consoleLevelName);

        final PipedOutputStream out = new PipedOutputStream();
        final PipedInputStream in = new PipedInputStream(out);
        try {
            new Thread(new Runnable() {
                public void run() {
                    try {
                        configuration.store(out, null);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        IOUtils.closeQuietly(out);
                    }
                }
            }).start();

            manager.readConfiguration(in);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }
}

From source file:org.ballerinalang.composer.server.launcher.log.LogManagerUtils.java

/**
 * Updating the default log manager.//from  w ww.j  a v  a2 s  .com
 * @throws IOException When log config file cannot be found.
 */
public void updateLogManager() throws IOException {
    // Modifying log manager property reading.
    LogManager logManager = LogManager.getLogManager();
    InputStream properties = this.readConfiguration();
    logManager.readConfiguration(properties);
}

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 .  ja v a2s  .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);
}