Example usage for java.util.logging ConsoleHandler ConsoleHandler

List of usage examples for java.util.logging ConsoleHandler ConsoleHandler

Introduction

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

Prototype

public ConsoleHandler() 

Source Link

Document

Create a ConsoleHandler for System.err .

Usage

From source file:com.freesundance.contacts.google.ContactsExample.java

/**
 * Run the example program.//  w  w w  .  j a  va  2s  .  com
 *
 * @param args Command-line arguments.
 */
public static void main(String[] args) throws ServiceException, IOException, GeneralSecurityException {

    ContactsExampleParameters parameters = new ContactsExampleParameters(args);
    if (parameters.isVerbose()) {
        httpRequestLogger.setLevel(Level.FINEST);
        ConsoleHandler handler = new ConsoleHandler();
        handler.setLevel(Level.FINEST);
        httpRequestLogger.addHandler(handler);
        httpRequestLogger.setUseParentHandlers(false);
    }

    if (parameters.numberOfParameters() == 0 || parameters.isHelp()
            || (parameters.getAction() == null && parameters.getScript() == null)) {
        displayUsage();
        return;
    }

    // Check that at most one of contactfeed and groupfeed has been provided
    if (parameters.isContactFeed() && parameters.isGroupFeed()) {
        throw new RuntimeException("Only one of contactfeed / groupfeed should" + "be specified");
    }

    ContactsExample example = new ContactsExample(parameters);

    processAction(example, parameters);
    System.out.flush();
}

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/*from  w  ww  .j a  v a2s  .c  o  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.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 . j a  v a2 s .c om*/
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:com.frostvoid.trekwar.server.TrekwarServer.java

/**
 * Initiates logging/*from ww w. j av a2s .co m*/
 *
 * @throws IOException
 */
private static void initLogging() throws IOException {
    FileHandler fh = new FileHandler(galaxyFileName + ".log");
    fh.setLevel(LOG.getLevel());
    Formatter logFormat = new Formatter() {

        @Override
        public String format(LogRecord rec) {
            StringBuilder buf = new StringBuilder(200);
            buf.append("#");
            buf.append(new java.util.Date());
            buf.append(' ');
            buf.append(rec.getLevel());
            buf.append(' ');
            buf.append(rec.getSourceClassName()).append(".").append(rec.getSourceMethodName());
            buf.append(":\n");
            buf.append(formatMessage(rec));
            buf.append('\n');
            return buf.toString();
        }
    };
    fh.setFormatter(logFormat);

    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(LOG.getLevel());
    Formatter conlogFormat = new Formatter() {
        @Override
        public String format(LogRecord rec) {
            StringBuilder buf = new StringBuilder(200);
            buf.append(rec.getLevel());
            buf.append(": ");
            buf.append(formatMessage(rec));
            buf.append('\n');
            return buf.toString();
        }
    };
    ch.setFormatter(conlogFormat);

    LOG.addHandler(fh);
    LOG.addHandler(ch);
}

From source file:test.db_memory.QualitativeTest.java

@Test(dataProvider = "quantitative", groups = "")
public static void testBasic(TestDescription test)
        throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
    Logger.getRootLogger().setLevel(org.apache.log4j.Level.ALL);
    java.util.logging.Logger.getGlobal().setLevel(Level.FINEST);
    java.util.logging.Logger.getGlobal().setUseParentHandlers(false);
    Handler newHandler = new ConsoleHandler();
    newHandler.setLevel(Level.FINEST);
    java.util.logging.Logger.getGlobal().addHandler(newHandler);

    CoreseTimer timerMemory = null;// ww  w.j  a  v  a  2 s .  c  o m
    CoreseTimer timerDb = null;
    try {
        setCacheForDb(test);
        System.gc();
        timerDb = CoreseTimer.build(test).setMode(CoreseTimer.Profile.DB).init().run();
        System.gc();
        timerMemory = CoreseTimer.build(test).setMode(CoreseTimer.Profile.MEMORY).init().run();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.out.println("running test: " + test.getId());
    boolean result;
    try {
        result = compareResults(timerDb.getMapping(), timerMemory.getMapping());
    } catch (Exception ex) {
        ex.printStackTrace();
        result = false;
    }
    test.setResultsEqual(result);
    timerDb.writeResults();
    timerDb.writeStatistics();
    timerMemory.writeResults();
    timerMemory.writeStatistics();
    //      writeResult(test, timerDb, timerMemory);
    assertTrue(result, test.getId());
}

From source file:org.syncany.cli.CommandLineClient.java

private void initLogHandlers(OptionSet options, OptionSpec<String> optionLog, OptionSpec<Void> optionLogPrint,
        OptionSpec<Void> optionDebug) throws SecurityException, IOException {

    // --log=<file>
    String logFilePattern = null;

    if (options.has(optionLog)) {
        if (!"-".equals(options.valueOf(optionLog))) {
            logFilePattern = options.valueOf(optionLog);
        }// w  ww  . j a va2  s . c om
    } else if (config != null && config.getLogDir().exists()) {
        logFilePattern = config.getLogDir() + File.separator + LOG_FILE_PATTERN;
    } else {
        logFilePattern = UserConfig.getUserLogDir() + File.separator + LOG_FILE_PATTERN;
    }

    if (logFilePattern != null) {
        Handler fileLogHandler = new FileHandler(logFilePattern, LOG_FILE_LIMIT, LOG_FILE_COUNT, true);
        fileLogHandler.setFormatter(new LogFormatter());

        Logging.addGlobalHandler(fileLogHandler);
    }

    // --debug, add console handler
    if (options.has(optionDebug) || options.has(optionLogPrint)
            || (options.has(optionLog) && "-".equals(options.valueOf(optionLog)))) {
        Handler consoleLogHandler = new ConsoleHandler();
        consoleLogHandler.setFormatter(new LogFormatter());

        Logging.addGlobalHandler(consoleLogHandler);
    }
}

From source file:org.owasp.proxy.Main.java

public static void main(String[] args) throws Exception {
    java.lang.System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
    logger.setUseParentHandlers(false);/*from  w ww  . ja  v  a  2 s  . c  om*/
    Handler ch = new ConsoleHandler();
    ch.setFormatter(new TextFormatter());
    logger.addHandler(ch);

    final Configuration config = Configuration.init(args);

    final InetSocketAddress listen = new InetSocketAddress(config.iface, config.port);
    TargetedConnectionHandler tch;
    if (config.httpConnect == null) {
        DefaultHttpRequestHandler drh = configureRequestHandler(config);
        ServerGroup sg = new ServerGroup();
        sg.addServer(listen);
        drh.setServerGroup(sg);

        HttpRequestHandler rh = drh;
        rh = configureAuthentication(rh, config);
        rh = configureAJP(rh, config);
        rh = new LoggingHttpRequestHandler(rh);
        rh = configureJDBCLogging(rh, config);
        rh = configureInterception(rh, config);

        HttpProxyConnectionHandler hpch = new HttpProxyConnectionHandler(rh);
        SSLContextSelector cp = getServerSSLContextSelector();
        tch = new SSLConnectionHandler(cp, true, hpch);
        tch = new LoopAvoidingTargetedConnectionHandler(sg, tch);
        hpch.setConnectHandler(tch);
    } else {
        tch = new ConnectConnectionHandler(config.httpConnect);
    }
    TargetedConnectionHandler socks = new SocksConnectionHandler(tch, true);
    Proxy p = new Proxy(listen, socks, null);
    p.setSocketTimeout(90000);
    p.start();

    System.out.println("Listener started on " + listen);
    System.out.println("Press Enter to terminate");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    p.stop();
    System.out.println("Terminated");
    System.exit(0);
}

From source file:org.ensembl.healthcheck.StandaloneTestRunner.java

public Logger getLogger() {
    if (logger == null) {
        logger = Logger.getLogger(StandaloneTestRunner.class.getCanonicalName());
        ConsoleHandler localConsoleHandler = new ConsoleHandler();
        localConsoleHandler.setFormatter(new Formatter() {
            DateFormat format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");

            @Override/* w ww .  j a va2  s.  c om*/
            public String format(LogRecord record) {
                return String.format("%s %s %s : %s%n", format.format(new Date(record.getMillis())),
                        record.getSourceClassName(), record.getLevel().toString(), record.getMessage());
            }
        });
        if (options.isVerbose()) {
            localConsoleHandler.setLevel(Level.ALL);
            logger.setLevel(Level.ALL);
        } else {
            localConsoleHandler.setLevel(Level.INFO);
            logger.setLevel(Level.INFO);
        }
        logger.setUseParentHandlers(false);
        logger.addHandler(localConsoleHandler);
    }
    return logger;
}

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

@RandomlyFails("never printed 'finished waiting'")
@Test/*  w w w.  j a v a2  s .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:com.redhat.rcm.version.Cli.java

private static void configureLogging(boolean useConsole, final boolean useLogFile, final File logFile) {
    System.out.println("Log file is: " + logFile.getAbsolutePath());

    final List<Handler> handlers = new ArrayList<Handler>();

    if (!useConsole && !useLogFile) {
        if (!useLogFile) {
            System.out.println(/*  w w  w  . j  a  v  a 2  s .  c o  m*/
                    "\n\nNOTE: --no-console option has been OVERRIDDEN since --no-log-file option was also provided.\nOutputting to console ONLY.\n");
            useConsole = true;
        }
    }

    if (useConsole) {
        final Handler chandler = new ConsoleHandler();
        chandler.setFormatter(new VManFormatter());
        chandler.setLevel(Level.ALL);
        handlers.add(chandler);
    }

    if (useLogFile) {
        try {
            final File dir = logFile.getParentFile();
            if (dir != null && !dir.isDirectory() && !dir.mkdirs()) {
                throw new RuntimeException(
                        "Failed to create parent directory for logfile: " + dir.getAbsolutePath());
            }
            final Handler fhandler = new FileHandler(logFile.getPath(), false);
            fhandler.setFormatter(new VManFormatter());
            fhandler.setLevel(Level.ALL);
            handlers.add(fhandler);
        } catch (final IOException e) {
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            System.out.printf("ERROR: Failed to initialize log file: %s. Reason: %s\n\n%s\n\n", logFile,
                    e.getMessage(), sw.toString());

            throw new RuntimeException("Failed to initialize logfile.");
        }
    }

    root.setUseParentHandlers(false);
    final Handler[] currenthandlers = root.getHandlers();
    for (final Handler h : currenthandlers) {
        h.close();
        root.removeHandler(h);
    }
    for (final Handler h : handlers) {
        root.addHandler(h);
    }
}