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:MailHandlerDemo.java

/**
 * Used debug problems with the logging.properties. The system property
 * java.security.debug=access,stack can be used to trace access to the
 * LogManager reset./*  w  w  w  . jav a 2s  .  c  om*/
 *
 * @param prefix a string to prefix the output.
 * @param err any PrintStream or null for System.out.
 */
@SuppressWarnings("UseOfSystemOutOrSystemErr")
private static void checkConfig(String prefix, PrintStream err) {
    if (prefix == null || prefix.trim().length() == 0) {
        prefix = "DEBUG";
    }

    if (err == null) {
        err = System.out;
    }

    try {
        err.println(prefix + ": java.version=" + System.getProperty("java.version"));
        err.println(prefix + ": LOGGER=" + LOGGER.getLevel());
        err.println(prefix + ": JVM id " + ManagementFactory.getRuntimeMXBean().getName());
        err.println(prefix + ": java.security.debug=" + System.getProperty("java.security.debug"));
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            err.println(prefix + ": SecurityManager.class=" + sm.getClass().getName());
            err.println(prefix + ": SecurityManager classLoader=" + toString(sm.getClass().getClassLoader()));
            err.println(prefix + ": SecurityManager.toString=" + sm);
        } else {
            err.println(prefix + ": SecurityManager.class=null");
            err.println(prefix + ": SecurityManager.toString=null");
            err.println(prefix + ": SecurityManager classLoader=null");
        }

        String policy = System.getProperty("java.security.policy");
        if (policy != null) {
            File f = new File(policy);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        }

        LogManager manager = LogManager.getLogManager();
        String key = "java.util.logging.config.file";
        String cfg = System.getProperty(key);
        if (cfg != null) {
            err.println(prefix + ": " + cfg);
            File f = new File(cfg);
            err.println(prefix + ": AbsolutePath=" + f.getAbsolutePath());
            err.println(prefix + ": CanonicalPath=" + f.getCanonicalPath());
            err.println(prefix + ": length=" + f.length());
            err.println(prefix + ": canRead=" + f.canRead());
            err.println(prefix + ": lastModified=" + new java.util.Date(f.lastModified()));
        } else {
            err.println(prefix + ": " + key + " is not set as a system property.");
        }
        err.println(prefix + ": LogManager.class=" + manager.getClass().getName());
        err.println(prefix + ": LogManager classLoader=" + toString(manager.getClass().getClassLoader()));
        err.println(prefix + ": LogManager.toString=" + manager);
        err.println(prefix + ": MailHandler classLoader=" + toString(MailHandler.class.getClassLoader()));
        err.println(
                prefix + ": Context ClassLoader=" + toString(Thread.currentThread().getContextClassLoader()));
        err.println(prefix + ": Session ClassLoader=" + toString(Session.class.getClassLoader()));
        err.println(prefix + ": DataHandler ClassLoader=" + toString(DataHandler.class.getClassLoader()));

        final String p = MailHandler.class.getName();
        key = p.concat(".mail.to");
        String to = manager.getProperty(key);
        err.println(prefix + ": TO=" + to);
        if (to != null) {
            err.println(prefix + ": TO=" + Arrays.toString(InternetAddress.parse(to, true)));
        }

        key = p.concat(".mail.from");
        String from = manager.getProperty(key);
        if (from == null || from.length() == 0) {
            Session session = Session.getInstance(new Properties());
            InternetAddress local = InternetAddress.getLocalAddress(session);
            err.println(prefix + ": FROM=" + local);
        } else {
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, false)));
            err.println(prefix + ": FROM=" + Arrays.asList(InternetAddress.parse(from, true)));
        }

        synchronized (manager) {
            final Enumeration<String> e = manager.getLoggerNames();
            while (e.hasMoreElements()) {
                final Logger l = manager.getLogger(e.nextElement());
                if (l != null) {
                    final Handler[] handlers = l.getHandlers();
                    if (handlers.length > 0) {
                        err.println(prefix + ": " + l.getClass().getName() + ", " + l.getName());
                        for (Handler h : handlers) {
                            err.println(prefix + ":\t" + toString(prefix, err, h));
                        }
                    }
                }
            }
        }
    } catch (Throwable error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }
    err.flush();
}

From source file:net.technicpack.launcher.LauncherMain.java

private static void setupLogging(LauncherDirectories directories, ResourceLoader resources) {
    System.out.println("Setting up logging");
    final Logger logger = Utils.getLogger();
    File logDirectory = new File(directories.getLauncherDirectory(), "logs");
    if (!logDirectory.exists()) {
        logDirectory.mkdir();/*  w  w  w.  java2s.com*/
    }
    File logs = new File(logDirectory, "techniclauncher_%D.log");
    RotatingFileHandler fileHandler = new RotatingFileHandler(logs.getPath());

    fileHandler.setFormatter(new BuildLogFormatter(resources.getLauncherBuild()));

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

    LauncherMain.consoleFrame = new ConsoleFrame(2500, resources.getImage("icon.png"));
    Console console = new Console(LauncherMain.consoleFrame, resources.getLauncherBuild());

    logger.addHandler(new ConsoleHandler(console));

    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) {
            e.printStackTrace();
            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);
            //                }
        }
    });
}

From source file:org.spoutcraft.launcher.Main.java

private static void setupLogger() {
    Logger logger = Logger.getLogger("launcher");
    File logDirectory = new File(Utils.getWorkingDirectory(), "logs");
    if (!logDirectory.exists()) {
        logDirectory.mkdir();//from   w  ww.  jav  a 2s. com
    }
    File logs = new File(logDirectory, "spoutcraft_%D.log");
    RotatingFileHandler fileHandler = new RotatingFileHandler(logs.getPath());

    fileHandler.setFormatter(new DateOutputFormatter(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")));

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

    Main.handler = fileHandler;

    logger.setUseParentHandlers(false);

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

From source file:net.sourceforge.pmd.junit.JavaUtilLoggingRule.java

/**
 * Creates a new rule, that attaches a custom log handler
 * to the given logger.//from w  w w.  j  a va  2 s .  com
 * @param loggerName the name of the logger to check
 */
public JavaUtilLoggingRule(String loggerName) {
    this.logger = Logger.getLogger(loggerName);
    this.stream = new ByteArrayOutputStream();

    Logger currentLogger = logger;
    while (currentLogger.getHandlers().length == 0) {
        currentLogger = currentLogger.getParent();
    }
    this.customLogHandler = new StreamHandler(stream, currentLogger.getHandlers()[0].getFormatter());
}

From source file:com.ning.jetty.core.listeners.SetupJULBridge.java

@Override
public void contextInitialized(final ServletContextEvent event) {
    // We first remove the default handler(s)
    final Logger rootLogger = LogManager.getLogManager().getLogger("");
    final Handler[] handlers = rootLogger.getHandlers();

    if (!ArrayUtils.isEmpty(handlers)) {
        for (final Handler handler : handlers) {
            rootLogger.removeHandler(handler);
        }//from   w w w . j a v  a  2 s  .  c o  m
    }
    // And then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j
    SLF4JBridgeHandler.install();
}

From source file:com.ning.metrics.action.binder.filters.SetupJULBridge.java

@Override
public void contextInitialized(final ServletContextEvent event) {
    // we first remove the default handler(s)
    final Logger rootLogger = LogManager.getLogManager().getLogger("");
    final Handler[] handlers = rootLogger.getHandlers();

    if (!ArrayUtils.isEmpty(handlers)) {
        for (Handler handler : handlers) {
            rootLogger.removeHandler(handler);
        }//from   w w  w  .  j a  va  2 s .  co  m
    }
    // and then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j (and thus log4j)
    SLF4JBridgeHandler.install();

    log.info("Assimilated java.util Logging");
}

From source file:com.ning.metrics.collector.endpoint.setup.SetupJULBridge.java

@Override
public void contextInitialized(final ServletContextEvent event) {
    // we first remove the default handler(s)
    final Logger rootLogger = LogManager.getLogManager().getLogger("");
    final Handler[] handlers = rootLogger.getHandlers();

    if (!ArrayUtils.isEmpty(handlers)) {
        for (final Handler handler : handlers) {
            rootLogger.removeHandler(handler);
        }/*from  www.  j  a v  a2  s  .  c om*/
    }
    // and then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j (and thus log4j)
    SLF4JBridgeHandler.install();

    log.info("Assimilated java.util Logging");
}

From source file:com.twitter.common.net.http.handlers.LogConfig.java

private void maybeAdjustHandlerLevels(Logger logger, Level newLevel) {
    do {//from  w w w.j a  v a 2 s .  co m
        for (Handler handler : logger.getHandlers()) {
            Level handlerLevel = handler.getLevel();
            if (newLevel.intValue() < handlerLevel.intValue()) {
                handler.setLevel(newLevel);
            }
        }
    } while (logger.getUseParentHandlers() && (logger = logger.getParent()) != null);
}

From source file:de.ailis.microblinks.blinks.compiler.Main.java

/**
 * Setups logging./*from  w ww .j  a v  a  2  s.c o m*/
 */
private void setupLogging() {
    final Logger logger = Logger.getLogger("");
    for (final Handler handler : logger.getHandlers()) {
        logger.removeHandler(handler);
    }
    logger.addHandler(new LogHandler(progName));
}

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);//from  w w  w.j a va 2  s  .c om

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

    return logger;
}