Example usage for java.util.logging Level parse

List of usage examples for java.util.logging Level parse

Introduction

In this page you can find the example usage for java.util.logging Level parse.

Prototype

public static synchronized Level parse(String name) throws IllegalArgumentException 

Source Link

Document

Parse a level name string into a Level.

Usage

From source file:io.stallion.boot.Booter.java

public void boot(String[] args, StallionJavaPlugin[] plugins) throws Exception {

    // Load the plugin jars, to get additional actions
    String targetPath = new File(".").getAbsolutePath();
    for (String arg : args) {
        if (arg.startsWith("-targetPath=")) {
            targetPath = StringUtils.split(arg, "=", 2)[1];
        }/*from   w w w. j a  v  a 2s .  co  m*/
    }
    if (!new File(targetPath).isDirectory() || empty(targetPath) || targetPath.equals("/")
            || targetPath.equals("/.")) {
        throw new CommandException(
                "You ran stallion with the target path " + targetPath + " but that is not a valid folder.");
    }

    PluginRegistry.loadWithJavaPlugins(targetPath, plugins);
    List<StallionRunAction> actions = new ArrayList(builtinActions);
    actions.addAll(PluginRegistry.instance().getAllPluginDefinedStallionRunActions());

    // Load the action executor
    StallionRunAction action = null;
    for (StallionRunAction anAction : actions) {
        if (empty(anAction.getActionName())) {
            throw new UsageException(
                    "The action class " + anAction.getClass().getName() + " has an empty action name");
        }
        if (args.length > 0 && anAction.getActionName().equals(args[0])) {
            action = anAction;
        }
    }
    if (action == null) {
        String msg = "\n\nError! You must pass in a valid action as the first command line argument. For example:\n\n"
                + ">stallion serve -port=8090 -targetPath=~/my-stallion-site\n";
        if (args.length > 0) {
            msg += "\n\nYou passed in '" + args[0] + "', which is not a valid action.\n";
        }
        msg += "\nAllowed actions are:\n\n";
        for (StallionRunAction anAction : actions) {
            //Log.warn("Action: {0} {1} {2}", action, action.getActionName(), action.getHelp());
            msg += anAction.getActionName() + " - " + anAction.getHelp() + "\n";
        }
        msg += "\n\nYou can get help about an action by running: >stallion <action> help\n\n";
        System.err.println(msg);
        System.exit(1);
    }

    // Load the command line options
    CommandOptionsBase options = action.newCommandOptions();

    CmdLineParser parser = new CmdLineParser(options);

    if (args.length > 1 && "help".equals(args[1])) {
        System.out.println(action.getActionName() + " - " + action.getHelp() + "\n\n");
        System.out.println("\n\nOptions for command " + action.getActionName() + "\n\n");
        parser.printUsage(System.out);
        System.exit(0);
    }

    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println("\n\nError!\n\n" + e.getMessage());
        System.err.println("\n\nAllowed options: \n");
        parser.printUsage(System.err);
        System.err.println("\n");
        System.exit(1);
    }

    options.setExtraPlugins(Arrays.asList(plugins));

    if (!empty(options.getLogLevel())) {
        try {
            Log.setLogLevel(Level.parse(options.getLogLevel()));
        } catch (IllegalArgumentException e) {
            System.err.println("\nError! Invalid log level: " + options.getLogLevel() + "\n\n"
                    + CommandOptionsBase.ALLOWED_LEVELS);
            System.exit(1);
        }
    }
    if (empty(options.getTargetPath())) {
        options.setTargetPath(new File(".").getAbsolutePath());
    }

    // Shutdown hooks
    Thread shutDownHookThread = new Thread() {
        public void run() {
            try {
                Unirest.shutdown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    shutDownHookThread.setName("stallion-shutdown-hook");
    Runtime.getRuntime().addShutdownHook(shutDownHookThread);

    // Execute the action
    action.loadApp(options);
    for (StallionJavaPlugin plugin : PluginRegistry.instance().getJavaPluginByName().values()) {
        plugin.preExecuteAction(action.getActionName(), options);
    }
    action.execute(options);

    if (!AppContextLoader.isNull()) {
        AppContextLoader.shutdown();
    }

}

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   w  w w  .  j av a  2s. com
            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.apache.geode.management.internal.cli.shell.GfshConfig.java

private static Level getLogLevel(final String logLevelString) {
    try {/* ww w. ja v a2s  .co  m*/
        String logLevelAsString = StringUtils.isBlank(logLevelString) ? "" : logLevelString.trim(); // trim
                                                                                                    // spaces
                                                                                                    // if
                                                                                                    // any
                                                                                                    // To support level NONE, used by GemFire
        if ("NONE".equalsIgnoreCase(logLevelAsString)) {
            logLevelAsString = Level.OFF.getName();
        }
        // To support level ERROR, used by GemFire, fall to WARNING
        if ("ERROR".equalsIgnoreCase(logLevelAsString)) {
            logLevelAsString = Level.WARNING.getName();
        }
        return Level.parse(logLevelAsString.toUpperCase());
    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage());
        return DEFAULT_LOGLEVEL;
    }
}

From source file:org.openCage.stroy.cli.Main.java

private void setLogLevel(String levelStr) {

    Log.setLevel(Level.parse(levelStr));
}

From source file:eu.edisonproject.training.wsd.BabelNet.java

@Override
public void configure(Properties properties) {
    super.configure(properties);
    keysStr = properties.getProperty("bablenet.key");
    keys = keysStr.split(",");
    key = keys[keyIndex];//  ww w .ja  va2  s. co m

    Level level = Level.parse(properties.getProperty("log.level", "INFO"));
    Handler[] handlers = Logger.getLogger("").getHandlers();
    for (int index = 0; index < handlers.length; index++) {
        handlers[index].setLevel(level);
    }
    LOGGER.setLevel(level);
}

From source file:hudson.plugins.selenium.PluginImpl.java

/**
 * @throws IOException//from w w  w  .ja va2  s .  c  o  m
 * @throws InterruptedException
 *
 */
private void startHub() throws IOException, InterruptedException {

    this.listener = new StreamTaskListener(getLogFile());

    channel = SeleniumProcessUtils.createSeleniumGridVM(listener);

    Level logLevel = Level.parse(getHubLogLevel());
    this.listener.getLogger().println("Starting Selenium Grid");

    List<String> args = new ArrayList<>();
    if (getNewSessionWaitTimeout() != null && getNewSessionWaitTimeout() >= 0) {
        args.add("-newSessionWaitTimeout");
        args.add(getNewSessionWaitTimeout().toString());
    }
    if (getMaxSession() != null && getMaxSession() > 0) {
        args.add("-maxSession");
        args.add(getMaxSession().toString());
    }
    if (getTimeout() != null) {
        args.add("-timeout");
        args.add(getTimeout().toString());
    }
    if (getBrowserTimeout() != null) {
        args.add("-browserTimeout");
        args.add(getBrowserTimeout().toString());
    }
    if (getThrowOnCapabilityNotPresent()) {
        args.add("-throwOnCapabilityNotPresent");
        args.add(Boolean.toString(getThrowOnCapabilityNotPresent()));
    }

    args.add("-host");
    args.add(getMasterHostName());

    hubLauncher = channel.callAsync(new HubLauncher(port, args.toArray(new String[args.size()]), logLevel));
}

From source file:pl.otros.logview.persistance.LogDataListPersistanceVer2.java

protected LogData parseLogData(String[] line, Map<String, Integer> fieldMapping) {
    for (int i = 0; i < line.length; i++) {
        line[i] = unescapgeString(line[i]);
    }//  w w  w .j  av  a2s .c om
    LogData ld = new LogData();
    ld.setId(Integer.parseInt(line[fieldMapping.get(HEADER_ID)]));
    ld.setClazz(line[fieldMapping.get(HEADER_CLASS)]);
    ld.setDate(new Date(Long.parseLong(line[fieldMapping.get(HEADER_TIMESTAMP)])));
    ld.setLevel(Level.parse(line[fieldMapping.get(HEADER_LEVEL)]));
    ld.setLoggerName(line[fieldMapping.get(HEADER_LOGGER)]);
    ld.setMessage(line[fieldMapping.get(HEADER_MESSAGE)]);
    ld.setMethod(line[fieldMapping.get(HEADER_METHOD)]);
    ld.setThread(line[fieldMapping.get(HEADER_THREAD)]);

    // Checking if field is set for backward compatibility
    if (fieldMapping.containsKey(HEADER_MDC)) {
        String p = line[fieldMapping.get(HEADER_MDC)];
        Properties pr = new Properties();
        try {
            pr.load(new ByteArrayInputStream(p.getBytes()));
            Map<String, String> m = new HashMap<String, String>();
            for (Object key : pr.keySet()) {
                m.put((String) key, (String) pr.get(key));
            }
            if (m.size() > 0) {
                ld.setProperties(m);
            }
        } catch (IOException e) {
            LOGGER.severe(
                    String.format("Can't load LogData (id=%d) properties: %s", ld.getId(), e.getMessage()));
        }
    }

    if (fieldMapping.containsKey(HEADER_NDC)) {
        ld.setNDC(line[fieldMapping.get(HEADER_NDC)]);
    }

    if (fieldMapping.containsKey(HEADER_FILE)) {
        ld.setFile(line[fieldMapping.get(HEADER_FILE)]);
    }

    if (fieldMapping.containsKey(HEADER_LINE)) {
        ld.setLine(line[fieldMapping.get(HEADER_LINE)]);
    }

    if (fieldMapping.containsKey(HEADER_LOG_SOURCE)) {
        ld.setLogSource(line[fieldMapping.get(HEADER_LOG_SOURCE)]);
    }

    if (fieldMapping.containsKey(HEADER_NOTE) && StringUtils.isNotBlank(line[fieldMapping.get(HEADER_NOTE)])) {
        ld.setNote(new Note(line[fieldMapping.get(HEADER_NOTE)]));
    }

    if (fieldMapping.containsKey(HEADER_MARKED)) {
        ld.setMarked(Boolean.parseBoolean(line[fieldMapping.get(HEADER_MARKED)]));
    }

    if (fieldMapping.containsKey(HEADER_MARKED_COLOR)
            && StringUtils.isNotBlank(line[fieldMapping.get(HEADER_MARKED_COLOR)])) {
        ld.setMarkerColors(MarkerColors.valueOf(line[fieldMapping.get(HEADER_MARKED_COLOR)]));
    }

    return ld;
}

From source file:pl.otros.logview.api.persistance.LogDataListPersistanceVer2.java

protected LogData parseLogData(String[] line, Map<String, Integer> fieldMapping) {
    for (int i = 0; i < line.length; i++) {
        line[i] = unescapedString(line[i]);
    }/*  www .  j ava  2s  .  c o  m*/
    LogData ld = new LogData();
    ld.setId(Integer.parseInt(line[fieldMapping.get(HEADER_ID)]));
    ld.setClazz(line[fieldMapping.get(HEADER_CLASS)]);
    ld.setDate(new Date(Long.parseLong(line[fieldMapping.get(HEADER_TIMESTAMP)])));
    ld.setLevel(Level.parse(line[fieldMapping.get(HEADER_LEVEL)]));
    ld.setLoggerName(line[fieldMapping.get(HEADER_LOGGER)]);
    ld.setMessage(line[fieldMapping.get(HEADER_MESSAGE)]);
    ld.setMethod(line[fieldMapping.get(HEADER_METHOD)]);
    ld.setThread(line[fieldMapping.get(HEADER_THREAD)]);

    // Checking if field is set for backward compatibility
    if (fieldMapping.containsKey(HEADER_MDC)) {
        String p = line[fieldMapping.get(HEADER_MDC)];
        Properties pr = new Properties();
        try {
            pr.load(new ByteArrayInputStream(p.getBytes()));
            Map<String, String> m = new HashMap<>();
            for (Object key : pr.keySet()) {
                m.put((String) key, (String) pr.get(key));
            }
            if (m.size() > 0) {
                ld.setProperties(m);
            }
        } catch (IOException e) {
            LOGGER.error(
                    String.format("Can't load LogData (id=%d) properties: %s", ld.getId(), e.getMessage()));
        }
    }

    if (fieldMapping.containsKey(HEADER_NDC)) {
        ld.setNDC(line[fieldMapping.get(HEADER_NDC)]);
    }

    if (fieldMapping.containsKey(HEADER_FILE)) {
        ld.setFile(line[fieldMapping.get(HEADER_FILE)]);
    }

    if (fieldMapping.containsKey(HEADER_LINE)) {
        ld.setLine(line[fieldMapping.get(HEADER_LINE)]);
    }

    if (fieldMapping.containsKey(HEADER_LOG_SOURCE)) {
        ld.setLogSource(line[fieldMapping.get(HEADER_LOG_SOURCE)]);
    }

    if (fieldMapping.containsKey(HEADER_NOTE) && StringUtils.isNotBlank(line[fieldMapping.get(HEADER_NOTE)])) {
        ld.setNote(new Note(line[fieldMapping.get(HEADER_NOTE)]));
    }

    if (fieldMapping.containsKey(HEADER_MARKED)) {
        ld.setMarked(Boolean.parseBoolean(line[fieldMapping.get(HEADER_MARKED)]));
    }

    if (fieldMapping.containsKey(HEADER_MARKED_COLOR)
            && StringUtils.isNotBlank(line[fieldMapping.get(HEADER_MARKED_COLOR)])) {
        ld.setMarkerColors(MarkerColors.valueOf(line[fieldMapping.get(HEADER_MARKED_COLOR)]));
    }

    return ld;
}

From source file:eu.edisonproject.training.wsd.DisambiguatorImpl.java

@Override
public void configure(Properties properties) {
    String numOfTerms = System.getProperty("num.of.terms");

    if (numOfTerms == null) {
        limit = Integer.valueOf(properties.getProperty("num.of.terms", "5"));
    } else {//ww w . java  2  s .  c o  m
        limit = Integer.valueOf(numOfTerms);
    }
    LOGGER.log(Level.FINE, "num.of.terms: {0}", limit);

    String offset = System.getProperty("offset.terms");

    if (offset == null) {
        lineOffset = Integer.valueOf(properties.getProperty("offset.terms", "1"));
    } else {
        lineOffset = Integer.valueOf(offset);
    }
    LOGGER.log(Level.FINE, "offset.terms: {0}", lineOffset);
    String minimumSimilarityStr = System.getProperty("minimum.similarity");
    if (minimumSimilarityStr == null) {
        minimumSimilarityStr = properties.getProperty("minimum.similarity", "0,3");
    }
    minimumSimilarity = Double.valueOf(minimumSimilarityStr);
    LOGGER.log(Level.FINE, "minimum.similarity: {0}", lineOffset);
    stopWordsPath = System.getProperty("stop.words.file");

    if (stopWordsPath == null) {
        stopWordsPath = properties.getProperty("stop.words.file",
                ".." + File.separator + "etc" + File.separator + "stopwords.csv");
    }
    LOGGER.log(Level.FINE, "stop.words.file: {0}", stopWordsPath);
    itemsFilePath = System.getProperty("itemset.file");
    if (itemsFilePath == null) {
        itemsFilePath = properties.getProperty("itemset.file",
                ".." + File.separator + "etc" + File.separator + "allTerms.csv");
    }
    LOGGER.log(Level.FINE, "itemset.file: {0}", itemsFilePath);
    //        Configuration config = HBaseConfiguration.create();
    //        try {
    //            conn = ConnectionFactory.createConnection(config);
    //        } catch (IOException ex) {
    //            LOGGER.log(Level.SEVERE, null, ex);
    //        }
    CharArraySet stopwordsCharArray = new CharArraySet(ConfigHelper.loadStopWords(stopWordsPath), true);
    tokenizer = new StopWord(stopwordsCharArray);
    lematizer = new StanfordLemmatizer();
    stemer = new Stemming();

    //        try {
    //            String logPropFile = properties.getProperty("logging.properties.file", ".." + File.separator + "etc" + File.separator + "log.properties");
    //            FileInputStream fis = new FileInputStream(logPropFile);
    //            LogManager.getLogManager().readConfiguration(fis);
    //        } catch (FileNotFoundException ex) {
    //            Logger.getLogger(DisambiguatorImpl.class.getName()).log(Level.WARNING, null, ex);
    //        } catch (IOException | SecurityException ex) {
    //            Logger.getLogger(DisambiguatorImpl.class.getName()).log(Level.WARNING, null, ex);
    //        }
    Level level = Level.parse(properties.getProperty("log.level", "INFO"));

    Handler[] handlers = Logger.getLogger("").getHandlers();
    for (int index = 0; index < handlers.length; index++) {
        handlers[index].setLevel(level);
    }
    LOGGER.setLevel(level);
}