Example usage for java.util.logging Logger addHandler

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

Introduction

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

Prototype

public void addHandler(Handler handler) throws SecurityException 

Source Link

Document

Add a log Handler to receive logging messages.

Usage

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
 *///  w  w w . jav  a 2  s  .  co 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);
}

From source file:pe.chalk.telegram.TelegramBot.java

public Logger initLogger(final Level level) {
    final Logger logger = this.getLogger();
    for (Handler handler : logger.getHandlers())
        logger.removeHandler(handler);/* w  w w. j av  a 2s . com*/

    logger.setUseParentHandlers(false);
    logger.addHandler(new StandardHandler(level));
    logger.setLevel(level);

    return logger;
}

From source file:org.deviceconnect.android.deviceplugin.theta.ThetaDeviceApplication.java

@Override
public void onCreate() {
    super.onCreate();

    if (BuildConfig.DEBUG) {
        for (Logger logger : mLoggers) {
            AndroidHandler handler = new AndroidHandler(logger.getName());
            handler.setFormatter(new SimpleFormatter());
            handler.setLevel(Level.ALL);
            logger.addHandler(handler);
            logger.setLevel(Level.ALL);
        }/*from  w ww .  j  av  a  2s.c o m*/
    } else {
        for (Logger logger : mLoggers) {
            logger.setLevel(Level.OFF);
        }
    }

    Context context = getApplicationContext();
    mDeviceMgr = new ThetaDeviceManager(context);
    mHeadTracker = new HeadTrackerWrapper(new DefaultHeadTracker(context));
    mSphericalViewApi = new SphericalViewApi(context);
}

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   w ww  . j a v  a  2s. 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: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   ww  w .  j av  a  2 s.  com
                 * 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:org.peercast.core.PeerCastApplication.java

private void installLogHandlers() {
    //        org.seamless.util.logging.LoggingUtil.resetRootHandler(
    //                new FixedAndroidLogHandler()
    //        );/*from  w  w w.j  a  va 2  s  .c o m*/
    Logger appLogger = Logger.getLogger(getPackageName());
    appLogger.setLevel(Level.FINEST);

    try {
        Logger rootLogger = Logger.getLogger("");
        rootLogger.setLevel(Level.INFO);

        String pat = getCacheDir().getAbsolutePath() + "/app%g.log";
        FileHandler handler = new FileHandler(pat, MAX_LOG_SIZE, 1, true);

        handler.setFormatter(new CsvFormatter());
        rootLogger.addHandler(handler);
    } catch (IOException e) {
        Log.e(TAG, "new FileHandler()", e);
    }
}

From source file:de.ailis.wlandsuite.cli.CLIProg.java

/**
 * Setups loggings./*from w  ww  .  j a  v  a 2  s  .c  o m*/
 */

private void setupLogging() {
    Logger logger;

    logger = Logger.getLogger("");
    for (final Handler handler : logger.getHandlers()) {
        logger.removeHandler(handler);
    }
    logger.addHandler(new LogHandler(this.progName));
}

From source file:com.bc.fiduceo.post.PostProcessingToolTest.java

@Test
public void testThatPostProcessingToolInCaseOfExceptionsPrintsTheErrorMessageAndContinueWithTheNextFile()
        throws Exception {
    final ArrayList<Path> mmdFiles = new ArrayList<>();
    mmdFiles.add(Paths.get("nonExistingFileOne"));
    mmdFiles.add(Paths.get("nonExistingFileTwo"));
    mmdFiles.add(Paths.get("nonExistingFileThree"));

    final Formatter formatter = new SimpleFormatter();
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final StreamHandler handler = new StreamHandler(stream, formatter);
    final Logger logger = FiduceoLogger.getLogger();
    FiduceoLogger.setLevelSilent();/*w w w .  j av a 2 s.c o  m*/

    try {
        logger.addHandler(handler);

        final PostProcessingContext context = new PostProcessingContext();
        final PostProcessingConfig processingConfig = getConfig();
        context.setProcessingConfig(processingConfig);

        final PostProcessingTool postProcessingTool = new PostProcessingTool(context);

        postProcessingTool.computeFiles(mmdFiles);

        handler.close();
        final String string = stream.toString();
        assertThat(string, CoreMatchers.containsString("nonExistingFileOne"));
        assertThat(string, CoreMatchers.containsString("nonExistingFileTwo"));
        assertThat(string, CoreMatchers.containsString("nonExistingFileThree"));
    } finally {
        logger.removeHandler(handler);
    }
}

From source file:com.cisco.oss.foundation.logging.FoundationLogger.java

private static void setupJULSupport(URL resource) {
    boolean julSupportEnabled = Boolean.valueOf(log4jConfigProps
            .getProperty(FoundationLoggerConstants.Foundation_JUL_SUPPORT_ENABLED.toString(), "false"));
    if (julSupportEnabled) {
        String appenderRef = log4jConfigProps
                .getProperty(FoundationLoggerConstants.Foundation_JUL_APPENDER_REF.toString());

        if (StringUtils.isBlank(appenderRef)) {

            Enumeration allAppenders = Logger.getRootLogger().getAllAppenders();

            while (allAppenders.hasMoreElements()) {

                Appender appender = (Appender) allAppenders.nextElement();

                if (appender instanceof FileAppender) {
                    appenderRef = appender.getName();
                    getLogger(FoundationLogger.class)
                            .info("*** Using '" + appenderRef + "' as the Java util logging appender ref ***");
                    System.err.println(
                            "*** Using '" + appenderRef + "' as the Java util logging appender ref ***");
                    break;
                }/*w  ww .  jav a  2  s .c o m*/
            }
        }

        if (StringUtils.isBlank(appenderRef)) {
            throw new IllegalArgumentException(
                    "Java util support was enabled but couldn't find a matching appender under the '"
                            + FoundationLoggerConstants.Foundation_JUL_APPENDER_REF.toString() + "' key.");
        }

        Handler handler = null;

        Appender appender = Logger.getRootLogger().getAppender(appenderRef);
        if (appender == null) {

            Enumeration allAppenders = Logger.getRootLogger().getAllAppenders();

            while (allAppenders.hasMoreElements()) {

                Appender tempAppender = (Appender) allAppenders.nextElement();

                if (tempAppender instanceof AsyncAppender) {

                    AsyncAppender asyncAppender = (AsyncAppender) tempAppender;
                    Enumeration asyncAppenderAllAppenders = asyncAppender.getAllAppenders();

                    while (asyncAppenderAllAppenders.hasMoreElements()) {

                        Appender asyncTempAppender = (Appender) asyncAppenderAllAppenders.nextElement();

                        if (appenderRef.equals(asyncTempAppender.getName())) {
                            appender = asyncTempAppender;
                            break;
                        }
                    }
                    if (appender != null) {
                        break;
                    }
                }
            }
        }

        if (appender instanceof FileAppender) {
            try {
                handler = new FileHandler(((FileAppender) appender).getFile());
            } catch (IOException e) {
                throw new IllegalArgumentException(
                        "IOException encountered when trying to setup jul logging: " + e, e);
            }
        } else if (appender instanceof ConsoleAppender) {
            handler = new ConsoleHandler();
        } else {
            getLogger(FoundationLogger.class)
                    .error("got a reference to an unsupported appender: " + appenderRef);
        }

        if (handler != null) {

            //                System.setProperty("java.util.logging.config.file",resource.getPath());

            java.util.logging.LogManager.getLogManager().reset();
            try {
                java.util.logging.LogManager.getLogManager().readConfiguration(resource.openStream());
            } catch (IOException e) {
                throw new IllegalArgumentException(
                        "IOException encountered when trying to read log4j properties file: " + e, e);
            }

            handler.setLevel(java.util.logging.Level.FINEST);
            handler.setFormatter(new FoundationLogFormatter());

            java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
            rootLogger.addHandler(handler);
            rootLogger.setLevel(java.util.logging.Level.SEVERE);

            Properties julLoggerSubset = getPropertiesSubset("jul.logger");
            if (!julLoggerSubset.isEmpty()) {
                Set<Object> keySet = julLoggerSubset.keySet();
                for (Object key : keySet) {
                    java.util.logging.Logger logger = java.util.logging.Logger.getLogger((String) key);
                    logger.setLevel(java.util.logging.Level.parse((String) julLoggerSubset.get(key)));
                }
            }
        }

    }
}

From source file:org.kalypso.model.hydrology.internal.test.OptimizeTest.java

private Logger createLogger(final File logFile) throws SecurityException, IOException {
    final Logger logger = Logger.getAnonymousLogger();
    final Handler[] handlers = logger.getHandlers();
    for (final Handler handler : handlers)
        logger.removeHandler(handler);/*ww w.  j  a va  2  s . co m*/

    final FileHandler fileHandler = new FileHandler(logFile.getAbsolutePath());
    logger.addHandler(fileHandler);

    return logger;
}