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.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java

@Test
public void buildShellScriptAcrossDisconnect() throws Exception {
    Assume.assumeFalse("TODO not sure how to write a corresponding batch script", Functions.isWindows());
    story.addStep(new Statement() {
        @SuppressWarnings("SleepWhileInLoop")
        @Override/*w w  w . j  a v a2 s .co  m*/
        public void evaluate() throws Throwable {
            Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName());
            LOGGER.setLevel(Level.FINE);
            Handler handler = new ConsoleHandler();
            handler.setLevel(Level.ALL);
            LOGGER.addHandler(handler);
            DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1",
                    Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP,
                    Collections.<NodeProperty<?>>emptyList());
            story.j.jenkins.addNode(s);
            startJnlpProc();
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "demo");
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            new FileOutputStream(f1).close();
            p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + "    sh 'touch \"" + f2
                    + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2
                    + "\"'\n" + "    echo 'OK, done'\n" + "}", true));
            WorkflowRun b = p.scheduleBuild2(0).waitForStart();
            while (!f2.isFile()) {
                Thread.sleep(100);
            }
            assertTrue(b.isBuilding());
            Computer c = s.toComputer();
            assertNotNull(c);
            killJnlpProc();
            while (c.isOnline()) {
                Thread.sleep(100);
            }
            startJnlpProc();
            while (c.isOffline()) {
                Thread.sleep(100);
            }
            assertTrue(f2.isFile());
            assertTrue(f1.delete());
            while (f2.isFile()) {
                Thread.sleep(100);
            }
            story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b));
            story.j.assertLogContains("finished waiting", b); // TODO sometimes is not printed to log, despite f2 having been removed
            story.j.assertLogContains("OK, done", b);
            killJnlpProc();
        }
    });
}

From source file:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java

@Test
public void buildShellScriptAcrossRestart() throws Exception {
    Assume.assumeFalse("TODO not sure how to write a corresponding batch script", Functions.isWindows());
    story.addStep(new Statement() {
        @SuppressWarnings("SleepWhileInLoop")
        @Override/*from  w w  w . jav  a  2  s .  co m*/
        public void evaluate() throws Throwable {
            Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName());
            LOGGER.setLevel(Level.FINE);
            Handler handler = new ConsoleHandler();
            handler.setLevel(Level.ALL);
            LOGGER.addHandler(handler);
            // Cannot use regular JenkinsRule.createSlave due to JENKINS-26398.
            // Nor can we can use JenkinsRule.createComputerLauncher, since spawned commands are killed by CommandLauncher somehow (it is not clear how; apparently before its onClosed kills them off).
            DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1",
                    Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP,
                    Collections.<NodeProperty<?>>emptyList());
            story.j.jenkins.addNode(s);
            startJnlpProc();
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "demo");
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            new FileOutputStream(f1).close();
            p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + "    sh 'touch \"" + f2
                    + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2
                    + "\"'\n" + "    echo 'OK, done'\n" + "}", true));
            WorkflowRun b = p.scheduleBuild2(0).waitForStart();
            while (!f2.isFile()) {
                Thread.sleep(100);
            }
            assertTrue(b.isBuilding());
            killJnlpProc();
        }
    });
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            WorkflowJob p = (WorkflowJob) story.j.jenkins.getItem("demo");
            WorkflowRun b = p.getLastBuild();
            assertTrue(b.isBuilding()); // TODO occasionally fails; log ends with: Running: Allocate node : Body : Start (no shell step in sight)
            startJnlpProc(); // Have to relaunch JNLP agent, since the Jenkins port has changed, and we cannot force JenkinsRule to reuse the same port as before.
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            assertTrue(f2.isFile());
            assertTrue(f1.delete());
            while (f2.isFile()) {
                Thread.sleep(100);
            }
            story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b));
            story.j.assertLogContains("finished waiting", b);
            story.j.assertLogContains("OK, done", b);
            killJnlpProc();
        }
    });
}

From source file:com.ellychou.todo.rest.service.SpringContextJerseyTest.java

/**
* Un-register {@link Handler log handler} from the list of root loggers.
*//*ww  w.  ja v  a 2s  . c om*/
private void unregisterLogHandler() {
    for (final Logger root : getRootLoggers()) {
        root.setLevel(logLevelMap.get(root));
        root.removeHandler(getLogHandler());
    }
    logHandler = null;
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

/**
 * Creates a new logger/*from  w  w  w  .  j a va2  s  .c o  m*/
 */
private Logger init(final Level level, final String file) {
    final LogSettings logSettings = settingsService.getLogSettings();
    final Logger logger = Logger.getAnonymousLogger();
    logger.setLevel(level);
    logger.setUseParentHandlers(false);
    try {
        final FileUnits units = logSettings.getMaxLengthPerFileUnits();
        final FileHandler fileHandler = new FileHandler(file,
                units.calculate(logSettings.getMaxLengthPerFile()), logSettings.getMaxFilesPerLog(), true);
        fileHandler.setFormatter(logFormatter);
        fileHandler.setEncoding(settingsService.getLocalSettings().getCharset());
        logger.addHandler(fileHandler);
    } catch (final Exception e) {
        final ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(logFormatter);
        try {
            consoleHandler.setEncoding(settingsService.getLocalSettings().getCharset());
        } catch (final Exception e1) {
            // Just ignore
        }
        logger.addHandler(consoleHandler);
        logger.log(Level.WARNING, "Unable to create logger for file " + file);
    }
    return logger;
}

From source file:org.jenkinsci.plugins.workflow.WorkflowTest.java

@RandomlyFails("never printed 'finished waiting'")
@Test//from w w w  .j  a va 2s .  c  o m
public void buildShellScriptAcrossDisconnect() throws Exception {
    story.addStep(new Statement() {
        @SuppressWarnings("SleepWhileInLoop")
        @Override
        public void evaluate() throws Throwable {
            Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName());
            LOGGER.setLevel(Level.FINE);
            Handler handler = new ConsoleHandler();
            handler.setLevel(Level.ALL);
            LOGGER.addHandler(handler);
            DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1",
                    Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP,
                    Collections.<NodeProperty<?>>emptyList());
            story.j.jenkins.addNode(s);
            startJnlpProc();
            p = story.j.jenkins.createProject(WorkflowJob.class, "demo");
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            new FileOutputStream(f1).close();
            p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + "    sh 'touch \"" + f2
                    + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2
                    + "\"'\n" + "    echo 'OK, done'\n" + "}"));
            startBuilding();
            while (!f2.isFile()) {
                Thread.sleep(100);
            }
            assertTrue(b.isBuilding());
            Computer c = s.toComputer();
            assertNotNull(c);
            killJnlpProc();
            while (c.isOnline()) {
                Thread.sleep(100);
            }
            startJnlpProc();
            while (c.isOffline()) {
                Thread.sleep(100);
            }
            assertTrue(f2.isFile());
            assertTrue(f1.delete());
            while (f2.isFile()) {
                Thread.sleep(100);
            }
            story.j.assertBuildStatusSuccess(JenkinsRuleExt.waitForCompletion(b));
            story.j.assertLogContains("finished waiting", b);
            story.j.assertLogContains("OK, done", b);
            killJnlpProc();
        }
    });
}

From source file:org.jenkinsci.plugins.workflow.WorkflowTest.java

@RandomlyFails("TODO isBuilding assertion after restart occasionally fails; log ends with: Running: Allocate node : Body : Start (no shell step in sight)")
@Test/* w  w  w  .ja  v  a  2s. c  o  m*/
public void buildShellScriptAcrossRestart() throws Exception {
    story.addStep(new Statement() {
        @SuppressWarnings("SleepWhileInLoop")
        @Override
        public void evaluate() throws Throwable {
            Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName());
            LOGGER.setLevel(Level.FINE);
            Handler handler = new ConsoleHandler();
            handler.setLevel(Level.ALL);
            LOGGER.addHandler(handler);
            // Cannot use regular JenkinsRule.createSlave due to JENKINS-26398.
            // Nor can we can use JenkinsRule.createComputerLauncher, since spawned commands are killed by CommandLauncher somehow (it is not clear how; apparently before its onClosed kills them off).
            DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1",
                    Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP,
                    Collections.<NodeProperty<?>>emptyList());
            story.j.jenkins.addNode(s);
            startJnlpProc();
            p = story.j.jenkins.createProject(WorkflowJob.class, "demo");
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            new FileOutputStream(f1).close();
            p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + "    sh 'touch \"" + f2
                    + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2
                    + "\"'\n" + "    echo 'OK, done'\n" + "}"));
            startBuilding();
            while (!f2.isFile()) {
                Thread.sleep(100);
            }
            assertTrue(b.isBuilding());
            killJnlpProc();
        }
    });
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            rebuildContext(story.j);
            assertTrue(b.isBuilding());
            startJnlpProc(); // Have to relaunch JNLP agent, since the Jenkins port has changed, and we cannot force JenkinsRule to reuse the same port as before.
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            assertTrue(f2.isFile());
            assertTrue(f1.delete());
            while (f2.isFile()) {
                Thread.sleep(100);
            }
            story.j.assertBuildStatusSuccess(JenkinsRuleExt.waitForCompletion(b));
            story.j.assertLogContains("finished waiting", b);
            story.j.assertLogContains("OK, done", b);
            killJnlpProc();
        }
    });
}

From source file:brut.apktool.Main.java

private static void setupLogging(Verbosity verbosity) {
    Logger logger = Logger.getLogger("");
    for (Handler handler : logger.getHandlers()) {
        logger.removeHandler(handler);//from w  w w .  j a v  a2  s  .c  o m
    }
    LogManager.getLogManager().reset();

    if (verbosity == Verbosity.QUIET) {
        return;
    }

    Handler handler = new Handler() {
        @Override
        public void publish(LogRecord record) {
            if (getFormatter() == null) {
                setFormatter(new SimpleFormatter());
            }

            try {
                String message = getFormatter().format(record);
                if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
                    System.err.write(message.getBytes());
                } else {
                    System.out.write(message.getBytes());
                }
            } catch (Exception exception) {
                reportError(null, exception, ErrorManager.FORMAT_FAILURE);
            }
        }

        @Override
        public void close() throws SecurityException {
        }

        @Override
        public void flush() {
        }
    };

    logger.addHandler(handler);

    if (verbosity == Verbosity.VERBOSE) {
        handler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);
    } else {
        handler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return record.getLevel().toString().charAt(0) + ": " + record.getMessage()
                        + System.getProperty("line.separator");
            }
        });
    }
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackTest.java

@Test
public void initSequence() throws IOException {
    Logger logger = Logger.getLogger(ProtocolStack.class.getName());
    CapturingHandler handler = new CapturingHandler();
    assertThat(logger.isLoggable(Level.FINEST), is(false));
    Level oldLevel = logger.getLevel();
    logger.addHandler(handler);//ww w  .  j  av a  2 s .c  o  m
    try {
        logger.setLevel(Level.FINEST);
        assertThat(logger.isLoggable(Level.FINEST), is(true));
        final AtomicInteger state = new AtomicInteger();
        ProtocolStack.on(new NetworkLayer(selector) {

            @Override
            protected void write(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void start() throws IOException {
                state.compareAndSet(0, 1);
            }

            @Override
            public void doCloseSend() throws IOException {

            }

            @Override
            public void doCloseRecv() {

            }

            @Override
            public boolean isSendOpen() {
                return true;
            }

        }).filter(new FilterLayer() {
            @Override
            public void start() throws IOException {
                state.compareAndSet(1, 2);
            }

            @Override
            public void onRecv(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doSend(@NonNull ByteBuffer data) throws IOException {

            }

        }).filter(new FilterLayer() {
            @Override
            public void start() throws IOException {
                state.compareAndSet(2, 3);
            }

            @Override
            public void onRecv(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doSend(@NonNull ByteBuffer data) throws IOException {

            }

        }).named("initSeq").build(new ApplicationLayer<Void>() {
            @Override
            public Void get() {
                return null;
            }

            @Override
            public void onRead(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void start() throws IOException {
                state.compareAndSet(3, 4);
            }

            @Override
            public void onReadClosed(IOException cause) throws IOException {

            }

            @Override
            public boolean isReadOpen() {
                return true;
            }

        });
        assertThat("Init in sequence", state.get(), is(4));
        assertThat(handler.logRecords,
                contains(
                        allOf(hasProperty("message", is("[{0}] Initializing")),
                                hasProperty("parameters", is(new Object[] { "initSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Starting")),
                                hasProperty("parameters", is(new Object[] { "initSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Started")),
                                hasProperty("parameters", is(new Object[] { "initSeq" })))));
    } finally {
        logger.removeHandler(handler);
        logger.setLevel(oldLevel);
    }
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

private StatsLogger() {
    try {//from w w  w  .j  ava 2s.c o m

        statsLog.setUseParentHandlers(false);
        statsLog.setLevel(Level.ALL);

        Logger uiLogger = Logger.getLogger("org.netbeans.ui");
        // org.netbeans.ui.focus = maybe too much info

        uiLogger.setUseParentHandlers(false);
        uiLogger.setLevel(Level.ALL);

        logSet = pref.get(Options.OptLogSet, "A");
        if (!changeHandler(makeLogHandler(logSet))) {
            Log.log("Stats logging init failed.");
            statsLog.setLevel(Level.OFF);
            uiLogger.setLevel(Level.OFF);
        }

    } catch (SecurityException ex) {
        Log.log(ex);
    }
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackTest.java

@Test
public void initSequenceFailure() throws IOException {
    Logger logger = Logger.getLogger(ProtocolStack.class.getName());
    CapturingHandler handler = new CapturingHandler();
    assertThat(logger.isLoggable(Level.FINEST), is(false));
    Level oldLevel = logger.getLevel();
    logger.addHandler(handler);//ww  w  . j a  v  a2  s . c  om
    try {
        logger.setLevel(Level.FINEST);
        assertThat(logger.isLoggable(Level.FINEST), is(true));
        final AtomicInteger state = new AtomicInteger();
        try {
            ProtocolStack.on(new NetworkLayer(selector) {

                @Override
                protected void write(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void start() throws IOException {
                    state.compareAndSet(0, 1);
                }

                @Override
                public void doCloseSend() throws IOException {

                }

                @Override
                public void doCloseRecv() {

                }

                @Override
                public boolean isSendOpen() {
                    return true;
                }

            }).filter(new FilterLayer() {
                @Override
                public void start() throws IOException {
                    state.compareAndSet(1, 2);
                    throw new IOException("boom");
                }

                @Override
                public void onRecv(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void doSend(@NonNull ByteBuffer data) throws IOException {

                }

            }).filter(new FilterLayer() {
                @Override
                public void start() throws IOException {
                    state.set(-2);
                }

                @Override
                public void onRecv(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void doSend(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void onRecvClosed(IOException cause) throws IOException {
                    state.compareAndSet(2, 3);
                    super.onRecvClosed(cause);
                }
            }).named("initSeq").build(new ApplicationLayer<Void>() {
                @Override
                public Void get() {
                    return null;
                }

                @Override
                public void onRead(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void start() throws IOException {
                    state.set(-3);
                }

                @Override
                public void onReadClosed(IOException cause) throws IOException {
                    state.compareAndSet(3, 4);
                }

                @Override
                public boolean isReadOpen() {
                    return true;
                }

            });
            fail("Expecting IOException");
        } catch (IOException e) {
            assertThat(e.getMessage(), is("boom"));
        }
        assertThat(handler.logRecords,
                contains(
                        allOf(hasProperty("message", is("[{0}] Initializing")),
                                hasProperty("parameters", is(new Object[] { "initSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Starting")),
                                hasProperty("parameters", is(new Object[] { "initSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Start failure")),
                                hasProperty("parameters", is(new Object[] { "initSeq" })),
                                hasProperty("thrown", hasProperty("message", is("boom"))))));
        assertThat("Init in sequence", state.get(), is(4));
    } finally {
        logger.removeHandler(handler);
        logger.setLevel(oldLevel);
    }
}