Example usage for java.util.logging Handler setLevel

List of usage examples for java.util.logging Handler setLevel

Introduction

In this page you can find the example usage for java.util.logging Handler setLevel.

Prototype

public synchronized void setLevel(Level newLevel) throws SecurityException 

Source Link

Document

Set the log level specifying which message levels will be logged by this Handler .

Usage

From source file:MailHandlerDemo.java

/**
 * Common fallback settings for a single handler.
 *
 * @param h the handler./*from  w  ww .  j a  va 2s.c o  m*/
 */
private static void fallbackSettings(Handler h) {
    if (h != null) {
        h.setErrorManager(new FileErrorManager());
        h.setLevel(Level.ALL);
    }
}

From source file:org.openqa.selenium.server.log.LoggingManager.java

public static void overrideSimpleFormatterWithTerseOneForConsoleHandler(Logger logger, boolean debugMode) {
    for (Handler handler : logger.getHandlers()) {
        if (handler instanceof ConsoleHandler) {
            final Formatter formatter;

            formatter = handler.getFormatter();
            if (formatter instanceof SimpleFormatter) {
                final StdOutHandler stdOutHandler;
                final Level originalLevel;

                /*/*from www .j  a v a2 s .c  o  m*/
                 * DGF - Nobody likes the SimpleFormatter; surely they wanted our terse formatter instead.
                 */
                originalLevel = handler.getLevel();
                handler.setFormatter(new TerseFormatter(false));
                handler.setLevel(Level.WARNING);

                /*
                 * Furthermore, we all want DEBUG/INFO on stdout and WARN/ERROR on stderr
                 */
                stdOutHandler = new StdOutHandler();
                stdOutHandler.setFormatter(new TerseFormatter(false));
                stdOutHandler.setFilter(new MaxLevelFilter(Level.INFO));
                stdOutHandler.setLevel(originalLevel);
                logger.addHandler(stdOutHandler);
                if (debugMode) {
                    if (originalLevel.intValue() > Level.FINE.intValue()) {
                        stdOutHandler.setLevel(Level.FINE);
                    }
                }
            }
        }
    }
}

From source file:hudson.cli.CLI.java

public static int _main(String[] _args) throws Exception {
    List<String> args = Arrays.asList(_args);
    PrivateKeyProvider provider = new PrivateKeyProvider();
    boolean sshAuthRequestedExplicitly = false;
    String httpProxy = null;//  w  w  w. ja  v a 2  s.  c  o  m

    String url = System.getenv("JENKINS_URL");

    if (url == null)
        url = System.getenv("HUDSON_URL");

    boolean tryLoadPKey = true;

    Mode mode = null;

    String user = null;
    String auth = null;

    String userIdEnv = System.getenv("JENKINS_USER_ID");
    String tokenEnv = System.getenv("JENKINS_API_TOKEN");

    boolean strictHostKey = false;

    while (!args.isEmpty()) {
        String head = args.get(0);
        if (head.equals("-version")) {
            System.out.println("Version: " + computeVersion());
            return 0;
        }
        if (head.equals("-http")) {
            if (mode != null) {
                printUsage("-http clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.HTTP;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-ssh")) {
            if (mode != null) {
                printUsage("-ssh clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.SSH;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-remoting")) {
            if (mode != null) {
                printUsage("-remoting clashes with previously defined mode " + mode);
                return -1;
            }
            mode = Mode.REMOTING;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-s") && args.size() >= 2) {
            url = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-noCertificateCheck")) {
            LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all.");
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            // bypass host name check, too.
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-noKeyAuth")) {
            tryLoadPKey = false;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-i") && args.size() >= 2) {
            File f = new File(args.get(1));
            if (!f.exists()) {
                printUsage(Messages.CLI_NoSuchFileExists(f));
                return -1;
            }

            provider.readFrom(f);

            args = args.subList(2, args.size());
            sshAuthRequestedExplicitly = true;
            continue;
        }
        if (head.equals("-strictHostKey")) {
            strictHostKey = true;
            args = args.subList(1, args.size());
            continue;
        }
        if (head.equals("-user") && args.size() >= 2) {
            user = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-auth") && args.size() >= 2) {
            auth = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-p") && args.size() >= 2) {
            httpProxy = args.get(1);
            args = args.subList(2, args.size());
            continue;
        }
        if (head.equals("-logger") && args.size() >= 2) {
            Level level = parse(args.get(1));
            for (Handler h : Logger.getLogger("").getHandlers()) {
                h.setLevel(level);
            }
            for (Logger logger : new Logger[] { LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER,
                    Logger.getLogger("org.apache.sshd") }) { // perhaps also Channel
                logger.setLevel(level);
            }
            args = args.subList(2, args.size());
            continue;
        }
        break;
    }

    if (url == null) {
        printUsage(Messages.CLI_NoURL());
        return -1;
    }

    if (auth == null) {
        // -auth option not set
        if (StringUtils.isNotBlank(userIdEnv) && StringUtils.isNotBlank(tokenEnv)) {
            auth = StringUtils.defaultString(userIdEnv).concat(":").concat(StringUtils.defaultString(tokenEnv));
        } else if (StringUtils.isNotBlank(userIdEnv) || StringUtils.isNotBlank(tokenEnv)) {
            printUsage(Messages.CLI_BadAuth());
            return -1;
        } // Otherwise, none credentials were set

    }

    if (!url.endsWith("/")) {
        url += '/';
    }

    if (args.isEmpty())
        args = Arrays.asList("help"); // default to help

    if (tryLoadPKey && !provider.hasKeys())
        provider.readFromDefaultLocations();

    if (mode == null) {
        mode = Mode.HTTP;
    }

    LOGGER.log(FINE, "using connection mode {0}", mode);

    if (user != null && auth != null) {
        LOGGER.warning("-user and -auth are mutually exclusive");
    }

    if (mode == Mode.SSH) {
        if (user == null) {
            // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same?
            LOGGER.warning("-user required when using -ssh");
            return -1;
        }
        return SSHCLI.sshConnection(url, user, args, provider, strictHostKey);
    }

    if (strictHostKey) {
        LOGGER.warning("-strictHostKey meaningful only with -ssh");
    }

    if (user != null) {
        LOGGER.warning("Warning: -user ignored unless using -ssh");
    }

    CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy);
    String userInfo = new URL(url).getUserInfo();
    if (userInfo != null) {
        factory = factory.basicAuth(userInfo);
    } else if (auth != null) {
        factory = factory.basicAuth(
                auth.startsWith("@") ? FileUtils.readFileToString(new File(auth.substring(1))).trim() : auth);
    }

    if (mode == Mode.HTTP) {
        return plainHttpConnection(url, args, factory);
    }

    CLI cli = factory.connect();
    try {
        if (provider.hasKeys()) {
            try {
                // TODO: server verification
                cli.authenticate(provider.getKeys());
            } catch (IllegalStateException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (UnsupportedOperationException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.warning("The server doesn't support public key authentication");
                    return -1;
                }
            } catch (GeneralSecurityException e) {
                if (sshAuthRequestedExplicitly) {
                    LOGGER.log(WARNING, null, e);
                    return -1;
                }
                LOGGER.warning("Failed to authenticate with your SSH keys. Proceeding as anonymous");
                LOGGER.log(FINE, null, e);
            }
        }

        // execute the command
        // Arrays.asList is not serializable --- see 6835580
        args = new ArrayList<String>(args);
        return cli.execute(args, System.in, System.out, System.err);
    } finally {
        cli.close();
    }
}

From source file:de.blinkenlights.bmix.main.Daemon.java

public void init(DaemonContext arg0) throws Exception {
    int verbosity = 1;
    if (System.getProperty("debugLevel") != null) {
        verbosity = Integer.parseInt(System.getProperty("debugLevel"));
    }/*from  ww w. j  a v  a2  s .c  o  m*/
    Level logLevel;
    if (verbosity == 0) {
        logLevel = Level.WARNING;
    } else if (verbosity == 1) {
        logLevel = Level.INFO;
    } else if (verbosity == 2) {
        logLevel = Level.FINE;
    } else if (verbosity >= 3) {
        logLevel = Level.FINEST;
    } else {
        System.err.println("Fatal Error: Invalid log verbosity: " + verbosity);
        return;
    }
    System.err.println("Setting log level to " + logLevel);
    Logger.getLogger("").setLevel(logLevel);
    for (Handler handler : Logger.getLogger("").getHandlers()) {
        handler.setLevel(logLevel);
    }

    bmix = new BMix("bmix.xml", false);
}

From source file:org.memento.client.Main.java

public void go(String[] args) throws ParseException, ClassCastException {
    boolean exit;
    CommandLine cmd;/*from   w ww. j a  v a  2  s .  c  om*/
    CommandLineParser parser;

    parser = new PosixParser();

    cmd = parser.parse(this.opts, args);
    exit = false;

    if (cmd.hasOption("h") || cmd.hasOption("help")) {
        this.printHelp(0);
    }

    if (cmd.hasOption("debug")) {
        Handler console = new ConsoleHandler();
        console.setLevel(Level.FINEST);

        Main.LOGGER.addHandler(console);
        Main.LOGGER.setLevel(Level.FINEST);
    } else {
        Main.LOGGER.setLevel(Level.OFF);
    }

    if (!cmd.hasOption("p")) {
        System.out.println("No port defined!");
        this.printHelp(2);
    }

    Main.LOGGER.fine("Main - Listen port " + cmd.getOptionValue("p"));
    try (Serve serve = new Serve(Integer.parseInt(cmd.getOptionValue("p")));) {
        if (cmd.hasOption("l")) {
            Main.LOGGER.fine("Listen address " + cmd.getOptionValue("l"));
            serve.setAddress(cmd.getOptionValue("l"));
        }

        if (cmd.hasOption("S")) {
            Main.LOGGER.fine("Main - SSL enabled");
            Section section = this.getOptions("ssl", cmd.getOptionValue("S"));
            serve.setSSL(true);

            serve.setSSLkey(section.get("key"));
            if (section.containsKey("password")) {
                Main.LOGGER.fine("Main - SSL key password exists");
                serve.setSSLpass(section.get("password"));
            }
        }

        serve.open();

        while (!exit) {
            try {
                exit = serve.listen();
            } catch (SocketException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, ex.getMessage());
            }
        }

    } catch (BindException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, ex.getMessage());
    } catch (IllegalArgumentException | SocketException | UnknownHostException | NullPointerException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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);
    }/*  ww  w .ja  v a 2 s  . c  o m*/
    logger.setLevel(level);
}

From source file:org.kalypso.ui.KalypsoGisPlugin.java

private void configureLogger() {
    // TODO:REMOVE THIS: we should always use the eclipse logging mechanisms
    final Logger logger = Logger.getLogger("org.kalypso"); //$NON-NLS-1$
    logger.setLevel(Level.INFO);//from   w  ww.  j  av  a  2 s . c om

    final Handler[] handlers = logger.getHandlers();
    for (final Handler handler : handlers) {
        handler.setLevel(Level.FINER);
    }
}

From source file:com.twitter.common.net.http.handlers.LogConfig.java

private void maybeAdjustHandlerLevels(Logger logger, Level newLevel) {
    do {//from   ww w . j  a  v  a2s . c o m
        for (Handler handler : logger.getHandlers()) {
            Level handlerLevel = handler.getLevel();
            if (newLevel.intValue() < handlerLevel.intValue()) {
                handler.setLevel(newLevel);
            }
        }
    } while (logger.getUseParentHandlers() && (logger = logger.getParent()) != null);
}

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);
                }//from  ww w.  j  a va  2  s .co m
            }
        }
        log.log(Level.INFO, SecurityUtil.adminAuditLogMessage(getContext().getRequest()));
    } else {
        throw new OpenStorefrontRuntimeException("Unable to find logger", "Check name");
    }

    return viewLoggers();
}

From source file:de.ailis.jasdoc.Main.java

/**
 * Initializes logging.//  w ww. j  a va2 s.c o  m
 */
private void initLogging() {
    final Logger logger = Logger.getLogger("de.ailis.jasdoc");
    logger.setUseParentHandlers(false);
    final Handler handler = new LogHandler();
    handler.setFilter(null);
    handler.setFormatter(new LogFormatter(this.debug));
    if (this.debug)
        handler.setLevel(Level.ALL);
    else if (this.quiet)
        handler.setLevel(Level.WARNING);
    else
        handler.setLevel(Level.INFO);
    logger.setFilter(null);
    logger.addHandler(handler);
    Logger.getLogger("").setLevel(handler.getLevel());
}