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:org.jenkinsci.plugins.workflow.cps.SnippetizerTest.java

@BeforeClass
public static void logging() {
    logger.setLevel(Level.ALL);/* w  w  w  . ja  v a2  s .co m*/
    Handler handler = new ConsoleHandler();
    handler.setLevel(Level.ALL);
    logger.addHandler(handler);
}

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

public void go(String[] args) throws ParseException, ClassCastException {
    boolean exit;
    CommandLine cmd;//from  w  w  w. j  av  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:net.kungfoo.grizzly.proxy.impl.Activator.java

private static void setup() throws IOReactorException {
    setupClient();//from ww w  .  ja va  2s. c om

    selectorThread = new SelectorThread();
    selectorThread.setPort(8282);
    ProxyAdapter httpProxy = new ProxyAdapter(connectingIOReactor);
    DefaultAsyncHandler handler = new DefaultAsyncHandler();
    handler.addAsyncFilter(new AsyncFilter() {
        @Override
        public boolean doFilter(AsyncExecutor asyncExecutor) {
            final AsyncTask asyncTask = asyncExecutor.getAsyncTask();
            final AsyncHandler asyncHandler = asyncExecutor.getAsyncHandler();
            DefaultProcessorTask task = (DefaultProcessorTask) asyncExecutor.getProcessorTask();
            task.getRequest().setAttribute(ProxyAdapter.CALLBACK_KEY, new Runnable() {
                @Override
                public void run() {
                    asyncHandler.handle(asyncTask);
                }
            });
            task.invokeAdapter();
            return false;
        }
    });
    selectorThread.setAsyncHandler(handler);
    selectorThread.setAdapter(httpProxy);
    selectorThread.setEnableAsyncExecution(true);
    selectorThread.setDisplayConfiguration(true);

    ProxyAdapter.logger.setLevel(Level.FINEST);
    ConsoleHandler consoleHandler = new ConsoleHandler();
    ProxyAdapter.logger.addHandler(consoleHandler);

    ProxyAdapter.logger.log(Level.FINE, "Setup done.");
}

From source file:fr.ippon.wip.util.WIPLogging.java

private WIPLogging() {
    try {/*from  w w w  .j a  v  a  2  s.  c o m*/
        // FileHandler launch an exception if parent path doesn't exist, so
        // we make sure it exists
        File logDirectory = new File(HOME + "/wip");
        if (!logDirectory.exists() || !logDirectory.isDirectory())
            logDirectory.mkdirs();

        accessFileHandler = new FileHandler("%h/wip/access.log", true);
        accessFileHandler.setLevel(Level.INFO);
        accessFileHandler.setFormatter(new SimpleFormatter());
        Logger.getLogger("fr.ippon.wip.http.hc.HttpClientExecutor.AccessLog").addHandler(accessFileHandler);

        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFilter(new Filter() {

            public boolean isLoggable(LogRecord record) {
                return !record.getLoggerName().equals("fr.ippon.wip.http.hc.HttpClientExecutor.AccessLog");
            }
        });

        Logger.getLogger("fr.ippon.wip").addHandler(consoleHandler);

        // For HttpClient debugging
        // FileHandler fileHandler = new
        // FileHandler("%h/wip/httpclient.log", true);
        // fileHandler.setLevel(Level.ALL);
        // Logger.getLogger("org.apache.http.headers").addHandler(fileHandler);
        // Logger.getLogger("org.apache.http.headers").setLevel(Level.ALL);

    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:plugins.GerritTriggerTest.java

@Before
public void setUpLogger() {
    LOGGER.setLevel(Level.ALL);/*from  w  ww.j av a 2 s .co  m*/
    LOGGER.setUseParentHandlers(false);
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(new SimpleFormatter());
    handler.setLevel(Level.ALL);
    LOGGER.addHandler(handler);
}

From source file:dk.hippogrif.prettyxml.PrettyPrint.java

static String loadConfiguration(String resource) {
    try {//  w  ww. j  av  a2  s .  c  om
        Properties prop = loadPropertiesResource(resource);

        // logging
        String loggingLevel = prop.getProperty("logging.Level");
        if (loggingLevel != null) {
            Level level = Level.parse(loggingLevel);
            Logger l = Logger.getLogger("dk.hippogrif.prettyxml");
            l.setLevel(level);
            if ("ConsoleHandler".equals(prop.getProperty("logging.Handler"))) {
                ConsoleHandler h = new ConsoleHandler();
                h.setLevel(level);
                l.addHandler(h);
            } else if ("FileHandler".equals(prop.getProperty("logging.Handler"))) {
                FileHandler h = new FileHandler(System.getProperty("user.home") + "/prettyxml.log");
                h.setLevel(level);
                l.addHandler(h);
            }
            logger.config("logging.Level=" + loggingLevel);
        }

        // version
        version = prop.getProperty("version", "");
        logger.config("version=" + version);

        // wellknown encodings
        String s = prop.getProperty("encodings");
        if (s == null) {
            throw new Exception("encodings missing in prettyxml.properties");
        }
        encodings = s.split(";");

        // wellknown property settings
        s = prop.getProperty("settings");
        if (s == null) {
            throw new Exception("settings missing in prettyxml.properties");
        }
        settings = s.split(";");
        setting = new HashMap();
        for (int i = 0; i < settings.length; i++) {
            String name = settings[i];
            Properties props = loadPropertiesResource(name + ".properties");
            checkProperties(props, false);
            setting.put(name, props);
        }

        // wellknown transformations
        s = prop.getProperty("transformations");
        if (s == null) {
            throw new Exception("transformations missing in prettyxml.properties");
        }
        transformations = s.split(";");
        transformation = new HashMap();
        for (int i = 0; i < transformations.length; i++) {
            String name = transformations[i];
            transformation.put(name, mkTransformerResource(name + ".xslt"));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return version;
}

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);/*from   www.j  av  a 2  s. c o m*/
    final ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.FINE);
    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:uk.ac.open.crc.jim.Jim.java

/**
 * Convenience constructor to create non static context to start
 * application.//  www  . ja v  a  2s .  co m
 *
 */
private Jim() {
    this.fileArgumentList = new ArrayList<>();
    this.settings = Settings.getInstance();
    // set up the log file
    try {
        fileHandler = new FileHandler(System.currentTimeMillis() / 1000 + "-jim-log.xml");
        LOGGER.addHandler(fileHandler);
        consoleHandler = new ConsoleHandler();
        consoleHandler.setLevel(Level.WARNING);
        LOGGER.addHandler(consoleHandler);
    } catch (IOException ioEx) {
        LOGGER.log(Level.SEVERE, "Cannot open log file for writing: {0}", ioEx.toString());
    }
    LOGGER.setLevel(Level.WARNING); // try to cut down the noise for other users
}

From source file:org.forgerock.openidm.patch.Main.java

/**
 * Executes the specified patch bundle.//from   w  w  w.j ava  2 s  . c om
 *
 * @param patchUrl          A URL specifying the location of the patch bundle
 * @param originalUrlString The String representation of the patch bundle location
 * @param workingDir        The working directory in which store logs and temporary files
 * @param installDir        The target directory against which the patch is to be applied
 * @param params            Additional patch specific parameters
 * @throws IOException      Thrown in the event of a failure creating the patch archive
 *                          or log files
 */
public static void execute(URL patchUrl, String originalUrlString, File workingDir, File installDir,
        Map<String, Object> params) throws IOException {

    try {
        // Load the base patch configuration
        InputStream in = CONFIG.getClass().getResourceAsStream(CONFIG_PROPERTIES_FILE);
        if (in == null) {
            throw new PatchException(
                    "Unable to locate: " + CONFIG_PROPERTIES_FILE + " in: " + patchUrl.toString());
        } else {
            CONFIG.load(in);
        }

        // Configure logging and disable parent handlers
        SingleLineFormatter formatter = new SingleLineFormatter();
        Handler historyHandler = new FileHandler(workingDir + File.separator + PATCH_HISTORY_FILE, true);
        Handler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(formatter);
        historyHandler.setFormatter(formatter);
        historyLogger.setUseParentHandlers(false);
        historyLogger.addHandler(consoleHandler);
        historyLogger.addHandler(historyHandler);

        // Initialize the Archive
        Archive archive = Archive.getInstance();
        archive.initialize(installDir, new File(workingDir, PATCH_ARCHIVE_DIR),
                CONFIG.getString(PATCH_BACKUP_ARCHIVE));

        // Create the patch logger once we've got the archive directory
        Handler logHandler = new FileHandler(archive.getArchiveDirectory() + File.separator + PATCH_LOG_FILE,
                false);
        logHandler.setFormatter(formatter);
        logger.setUseParentHandlers(false);
        logger.addHandler(logHandler);

        // Instantiate the patcgh implementation and invoke the patch
        Patch patch = instantiatePatch();
        patch.initialize(patchUrl, originalUrlString, workingDir, installDir, params);
        historyLogger.log(Level.INFO, "Applying {0}, version={1}",
                new Object[] { CONFIG.getProperty(PATCH_DESCRIPTION), CONFIG.getProperty(PATCH_RELEASE) });
        historyLogger.log(Level.INFO, "Target: {0}, Source: {1}", new Object[] { installDir, patchUrl });
        patch.apply();

        historyLogger.log(Level.INFO, "Completed");
    } catch (PatchException pex) {
        historyLogger.log(Level.SEVERE, "Failed", pex);
    } catch (ConfigurationException ex) {
        historyLogger.log(Level.SEVERE, "Failed to load patch configuration", ex);
    } finally {
        try {
            Archive.getInstance().close();
        } catch (IOException ex) {
            historyLogger.log(Level.SEVERE, "Failed to close patch archive", ex);
        }
    }
}

From source file:org.opencastproject.rest.RestServiceTestEnv.java

/**
 * Create an environment for <code>baseUrl</code>.
 * The base URL should be the URL where the service to test is mounted, e.g. http://localhost:8090/test
 *//*from w w w  .ja  v  a  2s  .  c o m*/
private RestServiceTestEnv(URL baseUrl, Option<? extends ResourceConfig> cfg) {
    this.baseUrl = baseUrl;
    this.cfg = cfg;
    // configure jersey logger to get some output in case of an error
    final Logger jerseyLogger = Logger.getLogger(com.sun.jersey.spi.inject.Errors.class.getName());
    jerseyLogger.addHandler(new ConsoleHandler());
    jerseyLogger.setLevel(Level.WARNING);
}