Example usage for java.util.logging Logger setLevel

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

Introduction

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

Prototype

public void setLevel(Level newLevel) throws SecurityException 

Source Link

Document

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

Usage

From source file:org.sglover.alfrescoextensions.common.MongoDbFactory.java

public MongoDbFactory(boolean enabled, String mongoURI, String dbName, boolean embedded) throws IOException {
    this.enabled = enabled;
    this.mongoURI = mongoURI;
    this.dbName = dbName;
    this.embedded = embedded;

    if (embedded) {
        final Logger mongoLogger = Logger.getLogger(MongoDbFactory.class.getName());
        mongoLogger.setLevel(Level.WARNING);
        final MongodStarter runtime = MongodStarter.getInstance(
                new RuntimeConfigBuilder().defaultsWithLogger(Command.MongoD, mongoLogger).build());
        mongodExecutable = runtime.prepare(newMongodConfig(Version.Main.PRODUCTION));
        mongodProcess = mongodExecutable.start();

        //            mongoFactory = MongodForTestsFactory.with(Version.Main.PRODUCTION);
    }//from  w w  w  . j av a  2s.  c om
}

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;//from   www  .  j  a  va2  s.  com

    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:org.bonitasoft.engine.api.HTTPServerAPITest.java

@Test(expected = ServerWrappedException.class)
public void invokeMethodCatchUndeclaredThrowableException() throws Exception {
    final PrintStream printStream = System.err;
    final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
    System.setErr(new PrintStream(myOut));
    final Logger logger = Logger.getLogger(HTTPServerAPI.class.getName());
    logger.setLevel(Level.FINE);
    final ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.FINE);//from w ww . j a  v  a 2s  . c  o  m
    logger.addHandler(ch);

    try {
        final Map<String, Serializable> options = new HashMap<String, Serializable>();
        final String apiInterfaceName = "apiInterfaceName";
        final String methodName = "methodName";
        final List<String> classNameParameters = new ArrayList<String>();
        final Object[] parametersValues = null;

        final HTTPServerAPI httpServerAPI = mock(HTTPServerAPI.class);
        final String response = "response";
        doReturn(response).when(httpServerAPI, "executeHttpPost", eq(options), eq(apiInterfaceName),
                eq(methodName), eq(classNameParameters), eq(parametersValues), Matchers.any(XStream.class));
        doThrow(new UndeclaredThrowableException(new BonitaException("Bonita exception"), "Exception plop"))
                .when(httpServerAPI, "checkInvokeMethodReturn", eq(response), Matchers.any(XStream.class));

        // Let's call it for real:
        doCallRealMethod().when(httpServerAPI).invokeMethod(options, apiInterfaceName, methodName,
                classNameParameters, parametersValues);
        httpServerAPI.invokeMethod(options, apiInterfaceName, methodName, classNameParameters,
                parametersValues);
    } finally {
        System.setErr(printStream);
        final String logs = myOut.toString();
        assertTrue("should have written in logs an exception",
                logs.contains("java.lang.reflect.UndeclaredThrowableException"));
        assertTrue("should have written in logs an exception", logs.contains("BonitaException"));
        assertTrue("should have written in logs an exception", logs.contains("Exception plop"));
    }
}

From source file:org.cloudifysource.esc.shell.commands.TeardownCloud.java

private void restoreLoggingLevel() {
    if (!verbose) {
        Set<Entry<String, Level>> entries = loggerStates.entrySet();
        for (Entry<String, Level> entry : entries) {
            Logger provisioningLogger = Logger.getLogger(entry.getKey());
            provisioningLogger.setLevel(entry.getValue());
        }/*  w  w  w  .  j  av a2s .c o  m*/
    }

}

From source file:org.geoserver.config.ServicePersisterTest.java

@Test
public void testRemoveWorkspaceLocalService() throws Exception {
    testAddWorkspaceLocalService();/*from  ww  w  .ja  v a2 s  . com*/

    File dataDirRoot = getTestData().getDataDirectoryRoot();
    WorkspaceInfo ws = getCatalog().getDefaultWorkspace();

    File f = new File(dataDirRoot, "workspaces" + "/" + ws.getName() + "/service.xml");
    assertTrue(f.exists());

    Logger logger = Logging.getLogger(GeoServerImpl.class);
    Level level = logger.getLevel();
    try {
        logger.setLevel(Level.OFF);
        ServiceInfo s = geoServer.getServiceByName(ws, "foo", ServiceInfo.class);
        geoServer.remove(s);
        assertFalse(f.exists());
    } finally {
        logger.setLevel(level);
    }
}

From source file:org.apache.aurora.common.net.http.handlers.LogConfig.java

@POST
@Produces(MediaType.TEXT_HTML)/*from   w  ww.  j a v a2  s  .c o  m*/
public String post(@FormParam("logger") String loggerName, @FormParam("level") String loggerLevel)
        throws TemplateException {

    Optional<String> configChange = Optional.empty();
    if (loggerName != null && loggerLevel != null) {
        Logger logger = Logger.getLogger(loggerName);
        Level newLevel = loggerLevel.equals("INHERIT") ? null : Level.parse(loggerLevel);
        logger.setLevel(newLevel);
        if (newLevel != null) {
            maybeAdjustHandlerLevels(logger, newLevel);
        }

        configChange = Optional.of(String.format("%s level changed to %s", loggerName, loggerLevel));
    }

    return displayPage(configChange);
}

From source file:com.cyberway.issue.io.Arc2Warc.java

protected void transform(final ARCReader reader, final File warc) throws IOException {
    WARCWriter writer = null;//from   ww w . ja va  2 s  .  c o  m
    // No point digesting. Digest is available after reading of ARC which
    // is too late for inclusion in WARC.
    reader.setDigest(false);
    try {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(warc));
        // Get the body of the first ARC record as a String so can dump it
        // into first record of WARC.
        final Iterator<ArchiveRecord> i = reader.iterator();
        ARCRecord firstRecord = (ARCRecord) i.next();
        ByteArrayOutputStream baos = new ByteArrayOutputStream((int) firstRecord.getHeader().getLength());
        firstRecord.dump(baos);
        // Add ARC first record content as an ANVLRecord.
        ANVLRecord ar = new ANVLRecord(1);
        ar.addLabelValue("Filedesc", baos.toString());
        List<String> metadata = new ArrayList<String>(1);
        metadata.add(ar.toString());
        // Now create the writer.  If reader was compressed, lets write
        // a compressed WARC.
        writer = new WARCWriter(null, bos, warc, reader.isCompressed(), null, metadata);
        // Write a warcinfo record with description about how this WARC
        // was made.
        writer.writeWarcinfoRecord(warc.getName(), "Made from " + reader.getReaderIdentifier() + " by "
                + this.getClass().getName() + "/" + getRevision());
        for (; i.hasNext();) {
            write(writer, (ARCRecord) i.next());
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (writer != null) {
            // I don't want the close being logged -- least, not w/o log of
            // an opening (and that'd be a little silly for simple script
            // like this). Currently, it logs at level INFO so that close
            // of files gets written to log files.  Up the log level just
            // for the close.
            Logger l = Logger.getLogger(writer.getClass().getName());
            Level oldLevel = l.getLevel();
            l.setLevel(Level.WARNING);
            try {
                writer.close();
            } finally {
                l.setLevel(oldLevel);
            }
        }
    }
}

From source file:org.apache.cxf.management.web.logging.atom.AbstractAtomBean.java

/**
 * Initializes bean; creates ATOM handler based on current properties state, and attaches handler to
 * logger(s).//  w  w w.java2  s .  com
 */
public void init() {
    checkInit();
    initialized = true;
    Handler h = createHandler();
    for (int i = 0; i < loggers.size(); i++) {
        Logger l = LogUtils.getL7dLogger(AbstractAtomBean.class, null, loggers.get(i).getLogger());
        l.addHandler(h);
        l.setLevel(LogLevel.toJUL(LogLevel.valueOf(loggers.get(i).getLevel())));
    }
}

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

@HandlesEvent("UpdateLogLevel")
public Resolution updateLogLevel() {
    Logger localLogger = LogManager.getLogManager().getLogger(logger);
    if (localLogger != null) {
        if (StringUtils.isNotBlank(level)) {
            localLogger.setLevel(Level.parse(level));
        } else {/*  w  w w .  j av  a2s. c o  m*/
            localLogger.setLevel(null);
        }
        log.log(Level.INFO, SecurityUtil.adminAuditLogMessage(getContext().getRequest()));
    } else {
        throw new OpenStorefrontRuntimeException("Unable to find logger", "Check name");
    }

    return viewLoggers();
}

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

protected void displayPage(final HttpServletRequest req, HttpServletResponse resp, final boolean posted)
        throws ServletException, IOException {
    writeTemplate(resp, new Closure<StringTemplate>() {
        @Override/*from  w w  w  .j a v a 2 s  . com*/
        public void execute(StringTemplate stringTemplate) {
            LoggingMXBean logBean = LogManager.getLoggingMXBean();

            if (posted) {
                String loggerName = req.getParameter("logger");
                String loggerLevel = req.getParameter("level");
                if (loggerName != null && loggerLevel != null) {
                    Logger logger = Logger.getLogger(loggerName);
                    Level newLevel = loggerLevel.equals("INHERIT") ? null : Level.parse(loggerLevel);
                    logger.setLevel(newLevel);
                    if (newLevel != null) {
                        maybeAdjustHandlerLevels(logger, newLevel);
                    }

                    stringTemplate.setAttribute("configChange",
                            String.format("%s level changed to %s", loggerName, loggerLevel));
                }
            }

            List<LoggerConfig> loggerConfigs = Lists.newArrayList();
            for (String logger : Ordering.natural().immutableSortedCopy(logBean.getLoggerNames())) {
                loggerConfigs.add(new LoggerConfig(logger, logBean.getLoggerLevel(logger)));
            }

            stringTemplate.setAttribute("loggers", loggerConfigs);
            stringTemplate.setAttribute("levels", LOG_LEVELS);
        }
    });
}