Example usage for java.util.logging Logger getHandlers

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

Introduction

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

Prototype

public Handler[] getHandlers() 

Source Link

Document

Get the Handlers associated with this logger.

Usage

From source file:com.twitter.heron.common.utils.logging.LoggingHelper.java

/**
 * Init java util logging//from w w w  .  j a  v a2 s  .  c  o  m
 *
 * @param level the Level of message to log
 * @param isRedirectStdOutErr whether we redirect std out&err
 * @param format the format to log
 */
public static void loggerInit(Level level, boolean isRedirectStdOutErr, String format) throws IOException {
    // Set the java util logging format
    setLoggingFormat(format);

    // Configure the root logger and its handlers so that all the
    // derived loggers will inherit the properties
    Logger rootLogger = Logger.getLogger("");
    for (Handler handler : rootLogger.getHandlers()) {
        handler.setLevel(level);
    }

    rootLogger.setLevel(level);

    if (rootLogger.getLevel().intValue() < Level.WARNING.intValue()) {
        // zookeeper logging scares me. if people want this, we can patch to config-drive this
        Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARNING);
    }

    // setting logging for http client to be error level
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "ERROR");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "ERROR");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "ERROR");

    if (isRedirectStdOutErr) {

        // Remove ConsoleHandler if present, to avoid StackOverflowError.
        // ConsoleHandler writes to System.err and since we are redirecting
        // System.err to Logger, it results in an infinite loop.
        for (Handler handler : rootLogger.getHandlers()) {
            if (handler instanceof ConsoleHandler) {
                rootLogger.removeHandler(handler);
            }
        }

        // now rebind stdout/stderr to logger
        Logger logger;
        LoggingOutputStream los;

        logger = Logger.getLogger("stdout");
        los = new LoggingOutputStream(logger, StdOutErrLevel.STDOUT);
        System.setOut(new PrintStream(los, true));

        logger = Logger.getLogger("stderr");
        los = new LoggingOutputStream(logger, StdOutErrLevel.STDERR);
        System.setErr(new PrintStream(los, true));
    }
}

From source file:geva.Main.Run.java

protected static void initJavaLogging(java.util.logging.Level level) {
    // All of the library code uses the commons logging library for output.
    // If you want to change the log formats or do anything fancy it's strongly
    // recommended that you switch to the much more capable log4j library as
    // described at http://commons.apache.org/logging/guide.html

    // As a default we'll make the JDK logging behave like System.out.println 
    // so we dont introduce another dependency.

    java.util.logging.SimpleFormatter fmt = new java.util.logging.SimpleFormatter() {
        @Override//w  w  w  .  j  a  v a2s.  com
        public synchronized String format(LogRecord record) {
            return record.getMessage() + "\n";
        }
    };
    java.util.logging.Handler handler = new java.util.logging.StreamHandler(System.out, fmt);
    java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
    for (java.util.logging.Handler h : rootLogger.getHandlers()) {
        rootLogger.removeHandler(h);
    }
    rootLogger.addHandler(handler);
    rootLogger.setLevel(level);

}

From source file:org.tros.utils.logging.Logging.java

public static void initLogging(BuildInfo binfo, Class init) {
    try {/*  ww w .  ja  v  a2s .  com*/
        //hack to get this logger to shut up
        Class<?> forName = Class.forName("org.reflections.Reflections");
        Field f = forName.getField("log");
        f.set(null, null);
    } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException
            | IllegalAccessException ex) {
        Logger.getLogger(Logging.class.getName()).log(Level.FINEST,
                "org.reflections.Reflections not in CLASSPATH...");
    }

    //make logs directory
    getLogDirectory(binfo);

    //init logger
    String dir = getApplicationEtcDirectory(binfo) + "/logging.properties";
    File logProp = new File(dir);
    if (!logProp.exists()) {
        copyFile(binfo, init, logProp);
    }

    if (logProp.exists()) {
        loadFile(logProp);
    }

    LogManager lm = LogManager.getLogManager();
    String property = lm.getProperty("version");
    if (property == null || !property.equals(binfo.getVersion().replace("-SNAPSHOT", ""))) {
        //backup old file
        File backup = new File(logProp.getAbsolutePath() + "." + (property == null ? "old" : property));
        logProp.renameTo(backup);
        //copy new file
        copyFile(binfo, init, logProp);
        //re-load new file
        loadFile(logProp);
    }

    //Small hack to close SwingComponentHandler which should only be used by a GUI
    //however, if the logging.properties file is already set with this handler, remove
    //it and then the GUI will manually re-add it in the LogConsole constructor.
    Logger logger = Logger.getLogger("");
    try {
        Class<?> swingLogger = Class.forName("org.tros.utils.logging.SwingComponentHandler");
        for (Handler h : logger.getHandlers()) {
            if (swingLogger.isAssignableFrom(h.getClass())) {
                logger.removeHandler(h);
                h.close();
            }
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Logging.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:de.fosd.jdime.config.JDimeConfig.java

/**
 * Set the logging level. The levels in descending order are:<br>
 *
 * <ul>//from  w  ww . j a va 2s  .c o m
 *  <li>ALL</li>
 *  <li>SEVERE (highest value)</li>
 *  <li>WARNING</li>
 *  <li>INFO</li>
 *  <li>CONFIG</li>
 *  <li>FINE</li>
 *  <li>FINER</li>
 *  <li>FINEST (lowest value)</li>
 *  <li>OFF</li>
 * </ul>
 *
 * @param logLevel
 *             one of the valid log levels according to {@link Level#parse(String)}
 */
public static void setLogLevel(String logLevel) {
    Level level;

    try {
        level = Level.parse(logLevel.toUpperCase());
    } catch (IllegalArgumentException e) {
        LOG.warning(
                () -> "Invalid log level %s. Must be one of OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST or ALL.");
        return;
    }

    Logger root = Logger.getLogger(Main.class.getPackage().getName());
    root.setLevel(level);

    for (Handler handler : root.getHandlers()) {
        handler.setLevel(level);
    }
}

From source file:ffx.Main.java

/**
 * Replace the default console handler with our custom FFX handler.
 *//*from  w  ww .j  a v a  2  s. c o m*/
private static void startLogging() {
    // Remove all log handlers from the default logger.
    try {
        Logger defaultLogger = LogManager.getLogManager().getLogger("");
        Handler defaultHandlers[] = defaultLogger.getHandlers();
        for (Handler h : defaultHandlers) {
            defaultLogger.removeHandler(h);
        }
    } catch (Exception e) {
        System.err.println(e.toString());
    }

    // Retrieve the log level from the ffx.log system property.
    String logLevel = System.getProperty("ffx.log", "info");
    Level tempLevel;
    try {
        tempLevel = Level.parse(logLevel.toUpperCase());
    } catch (Exception e) {
        tempLevel = Level.INFO;
    }

    level = tempLevel;
    logHandler = new LogHandler();
    logHandler.setLevel(level);
    Logger ffxLogger = Logger.getLogger("ffx");
    ffxLogger.addHandler(logHandler);
    ffxLogger.setLevel(level);
}

From source file:org.openstreetmap.josm.data.cache.JCSCacheManager.java

@SuppressWarnings("resource")
private static void initialize() throws IOException {
    File cacheDir = new File(Main.pref.getCacheDirectory(), "jcs");

    if (!cacheDir.exists() && !cacheDir.mkdirs())
        throw new IOException("Cannot access cache directory");

    File cacheDirLockPath = new File(cacheDir, ".lock");
    if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
        LOG.log(Level.WARNING, "Cannot create cache dir lock file");
    }/*  w  w  w. j  a  va2 s. c o m*/
    cacheDirLock = new FileOutputStream(cacheDirLockPath).getChannel().tryLock();

    if (cacheDirLock == null)
        LOG.log(Level.WARNING, "Cannot lock cache directory. Will not use disk cache");

    // raising logging level gives ~500x performance gain
    // http://westsworld.dk/blog/2008/01/jcs-and-performance/
    final Logger jcsLog = Logger.getLogger("org.apache.commons.jcs");
    jcsLog.setLevel(Level.INFO);
    jcsLog.setUseParentHandlers(false);
    // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
    Arrays.stream(jcsLog.getHandlers()).forEach(jcsLog::removeHandler);
    jcsLog.addHandler(new Handler() {
        final SimpleFormatter formatter = new SimpleFormatter();

        @Override
        public void publish(LogRecord record) {
            String msg = formatter.formatMessage(record);
            if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
                Logging.error(msg);
            } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
                Logging.warn(msg);
                // downgrade INFO level to debug, as JCS is too verbose at INFO level
            } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
                Logging.debug(msg);
            } else {
                Logging.trace(msg);
            }
        }

        @Override
        public void flush() {
            // nothing to be done on flush
        }

        @Override
        public void close() {
            // nothing to be done on close
        }
    });

    // this could be moved to external file
    Properties props = new Properties();
    // these are default common to all cache regions
    // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
    // CHECKSTYLE.OFF: SingleSpaceSeparator
    props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName());
    props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
    props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true");
    props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
    props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName());
    props.setProperty("jcs.default.elementattributes.IsEternal", "false");
    props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL));
    props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL));
    props.setProperty("jcs.default.elementattributes.IsSpool", "true");
    // CHECKSTYLE.ON: SingleSpaceSeparator
    CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
    cm.configure(props);
    cacheManager = cm;
}

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 ww w.  j a v  a 2s  .  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.spoutcraft.launcher.entrypoint.SpoutcraftLauncher.java

protected static Logger setupLogger() {
    final Logger logger = Utils.getLogger();
    File logDirectory = new File(Utils.getLauncherDirectory(), "logs");
    if (!logDirectory.exists()) {
        logDirectory.mkdir();//  w  w w.  j  a v  a2s . c  o  m
    }
    File logs = new File(logDirectory, "techniclauncher_%D.log");
    RotatingFileHandler fileHandler = new RotatingFileHandler(logs.getPath());

    fileHandler.setFormatter(new TechnicLogFormatter());

    for (Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
    logger.addHandler(fileHandler);

    SpoutcraftLauncher.handler = fileHandler;

    if (params != null && !params.isDebugMode()) {
        logger.setUseParentHandlers(false);

        System.setOut(new PrintStream(new LoggerOutputStream(console, Level.INFO, logger), true));
        System.setErr(new PrintStream(new LoggerOutputStream(console, Level.SEVERE, logger), true));
    }

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.log(Level.SEVERE, "Unhandled Exception in " + t, e);

            if (errorDialog == null) {
                LauncherFrame frame = null;

                try {
                    frame = Launcher.getFrame();
                } catch (Exception ex) {
                    //This can happen if we have a very early crash- before Launcher initializes
                }

                errorDialog = new ErrorDialog(frame, e);
                errorDialog.setVisible(true);
            }
        }
    });

    return logger;
}

From source file:com.surfs.nas.log.LogFactory.java

/**
 *
 *
 * @param filename/*from  www  .  j a v  a 2 s  .  co  m*/
 * @param log
 */
public static void configJDKLog(String filename, Logger log) {
    try {
        File f = new File(filename);
        if (!f.exists()) {
            return;
        }
        java.util.logging.LogManager.getLogManager().readConfiguration(new FileInputStream(f));
        java.util.logging.Logger logger = java.util.logging.LogManager.getLogManager().getLogger("");
        java.util.logging.Handler[] handlers = logger.getHandlers();
        for (java.util.logging.Handler h : handlers) {
            logger.removeHandler(h);
        }
        JdkLogHandler handle = new JdkLogHandler(log);
        logger.addHandler(handle);

    } catch (Exception e) {
    }
}

From source file:com.l2jfree.L2Config.java

/** Flushes all pending log entries. */
// FIXME MMOLogger.flush()
public static void flush() {
    // those are redirected to loggers, so flush them first
    System.out.flush();// ww  w .  j ava  2 s. c  o m
    System.err.flush();

    // then flush the loggers themselves
    final LogManager logManager = LogManager.getLogManager();

    for (String loggerName : Collections.list(logManager.getLoggerNames())) {
        if (loggerName == null)
            continue;

        final Logger logger = logManager.getLogger(loggerName);

        if (logger == null)
            continue;

        for (Handler handler : logger.getHandlers())
            if (handler != null)
                handler.flush();
    }

    // and finally the real console streams
    L2Config.out.flush();
    L2Config.err.flush();
}