Example usage for java.util.logging Handler getClass

List of usage examples for java.util.logging Handler getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:MailHandlerDemo.java

/**
 * Gets a formatting string describing the given handler.
 *
 * @param prefix the output prefix./*from   w  w  w  .  ja v  a2  s  .co m*/
 * @param err the error stream.
 * @param h the handler.
 * @return the formatted string.
 */
private static String toString(String prefix, PrintStream err, Handler h) {
    StringBuilder buf = new StringBuilder();
    buf.append(h.getClass().getName());
    try {
        if (h instanceof MailHandler) {
            MailHandler mh = (MailHandler) h;
            buf.append(", ").append(mh.getSubject());
        }
    } catch (SecurityException error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }

    try {
        buf.append(", ").append(h.getFormatter());
    } catch (SecurityException error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }

    try {
        if (h instanceof MailHandler) {
            MailHandler mh = (MailHandler) h;
            buf.append(", ").append(Arrays.toString(mh.getAttachmentFormatters()));
        }
    } catch (SecurityException error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }

    try {
        buf.append(", ").append(h.getLevel());
    } catch (SecurityException error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }

    try {
        buf.append(", ").append(h.getFilter());
    } catch (SecurityException error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }

    try {
        buf.append(", ").append(h.getErrorManager());
    } catch (SecurityException error) {
        err.print(prefix + ": ");
        error.printStackTrace(err);
    }

    buf.append(", ").append(toString(h.getClass().getClassLoader()));
    return buf.toString();
}

From source file:edu.usu.sdl.openstorefront.web.action.admin.LoggingAction.java

@HandlesEvent("UpdateHandlerLevel")
public Resolution updateHandlerLevel() {
    Logger localLogger = LogManager.getLogManager().getLogger(logger);
    if (localLogger != null) {

        for (Handler handlerLocal : localLogger.getHandlers()) {
            if (handlerLocal.getClass().getName().equals(handler)) {
                if (StringUtils.isNotBlank(level)) {
                    handlerLocal.setLevel(Level.parse(level));
                } else {
                    handlerLocal.setLevel(null);
                }/*from w w w . java 2s. c o  m*/
            }
        }
        log.log(Level.INFO, SecurityUtil.adminAuditLogMessage(getContext().getRequest()));
    } else {
        throw new OpenStorefrontRuntimeException("Unable to find logger", "Check name");
    }

    return viewLoggers();
}

From source file:com.googlecode.arit.jul.HandlerResourceScanner.java

public void clean(ClassLoader classLoader) {
    Enumeration<String> loggerNames = logManager.getLoggerNames();
    while (loggerNames.hasMoreElements()) {
        Logger logger = logManager.getLogger(loggerNames.nextElement());
        // On some JREs, Logger instances may be garbage collected. In this case,
        // the enumeration returned by getLoggerNames may contain names of garbage
        // collected loggers, and getLogger will return null for these names.
        // This was observed with Sun JRE 1.6. Loggers are not garbage collectable
        // with Sun JRE 1.5, IBM JRE 1.5 and IBM JRE 1.6 (WAS 7.0).
        if (logger != null) {
            Handler[] handlers = logger.getHandlers();
            for (Handler handler : handlers) {
                if (classLoader.equals(handler.getClass().getClassLoader())) {
                    logger.removeHandler(handler);
                    LOG.info("Removed JUL handler " + handler.getClass().getName());
                }//  www. j  a v  a  2  s .c om
            }
        }
    }
}

From source file:edu.usu.sdl.openstorefront.web.action.admin.LoggingAction.java

@DefaultHandler
public Resolution viewLoggers() {
    StringBuilder results = new StringBuilder();

    List<String> allLoggers = LogManager.getLoggingMXBean().getLoggerNames();
    Collections.sort(allLoggers);
    results.append(/*from  w w  w  .  j a  v a2 s .  c o  m*/
            "<table border='1'><tr style='background-color: lightgrey; '><th >Logger</th><th>Level</th><th>Handlers</th>");
    for (String name : allLoggers) {
        results.append("<tr>");
        Level levelLocal = LogManager.getLogManager().getLogger(name).getLevel();
        String levelName = "";
        if (levelLocal != null) {
            levelName = levelLocal.getName();
        }
        results.append("<td><b>").append(name).append("</b></td><td> ").append(levelName).append("</td>");

        results.append("<td>");
        Logger localLogger = LogManager.getLogManager().getLogger(name);
        for (Handler handlerLocal : localLogger.getHandlers()) {
            results.append(handlerLocal.getClass().getName()).append(" = ")
                    .append(handlerLocal.getLevel().getName()).append("<br>");
        }
        results.append("</td>");

        results.append("</tr>");
    }
    results.append("</table>");
    return new StreamingResolution("text/html", results.toString());
}

From source file:eu.asterics.mw.services.AstericsErrorHandling.java

/**
 * This method creates the logger. Actually there are 4 types of loggers: 
 * "severe": logs fatal errors i.e. errors that prevent the ARE from functioning
 * "warning": logs errors other than fatal e.g. component errors
 * "info": logs informative messages/*  w w w.ja v a  2  s .c o  m*/
 * "fine": logs debugging messages
 * 
 * Each logger by default also logs all messages with severity level higher than its own. 
 * E.g. the warning logger logs warning and severe messages, the info logger logs info, 
 * warning and severe messages etc. The same applies to the consoleHandler, i.e. by 
 * setting its level to info, the console will also print severe and warning messages 
 * along with info messages
 */
public Logger getLogger() {
    if (logger == null) {
        logger = Logger.getLogger("AstericsLogger");

        FileHandler warningFileHandler, severeFileHandler, infoFileHandler, fineFileHandler;
        ConsoleHandler consoleHandler;
        try {
            //cleanup before starting:
            logger.setUseParentHandlers(false);

            // remove and handlers that will be replaced
            Handler[] handlers = logger.getHandlers();
            for (Handler handler : handlers) {
                if (handler.getClass() == ConsoleHandler.class)
                    logger.removeHandler(handler);
            }

            File logFolder = new File(System.getProperty(LOG_PATH_PROPERTY, ResourceRegistry.TMP_FOLDER));
            if (!logFolder.exists()) {
                FileUtils.forceMkdir(logFolder);
            }
            //Create handlers
            severeFileHandler = new FileHandler(new File(logFolder, "asterics_logger_severe.log").getPath(),
                    true);
            warningFileHandler = new FileHandler(new File(logFolder, "asterics_logger_warning.log").getPath(),
                    true);
            infoFileHandler = new FileHandler(new File(logFolder, "asterics_logger.log").getPath(), true);
            fineFileHandler = new FileHandler(new File(logFolder, "asterics_logger_fine.log").getPath(), true);
            consoleHandler = new ConsoleHandler();

            //Set report level of handlers
            severeFileHandler.setLevel(Level.SEVERE);
            warningFileHandler.setLevel(Level.WARNING);
            infoFileHandler.setLevel(Level.INFO);
            fineFileHandler.setLevel(Level.FINE);

            //The consoleHandler prints log messaged to the console. Its 
            //severety level can be adjusted accordingly. 
            String level = getLoggerLevel();
            switch (level) {
            case "INFO":
                consoleHandler.setLevel(Level.INFO);
                break;
            case "WARNING":
                consoleHandler.setLevel(Level.WARNING);
                break;
            case "FINE":
                consoleHandler.setLevel(Level.FINE);
                break;
            case "SEVERE":
                consoleHandler.setLevel(Level.SEVERE);
                break;

            default:
                consoleHandler.setLevel(Level.INFO);
                break;
            }

            //Add handlers to the logger
            logger.addHandler(warningFileHandler);
            logger.addHandler(severeFileHandler);
            logger.addHandler(infoFileHandler);
            logger.addHandler(fineFileHandler);
            logger.addHandler(consoleHandler);

            //Create formatters for the handlers (optional)
            severeFileHandler.setFormatter(new SimpleFormatter());
            warningFileHandler.setFormatter(new SimpleFormatter());
            infoFileHandler.setFormatter(new SimpleFormatter());
            fineFileHandler.setFormatter(new SimpleFormatter());
            consoleHandler.setFormatter(new SimpleFormatter());

            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);

        } catch (SecurityException e) {
            System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: "
                    + e.getMessage());
        } catch (IOException e) {
            //logger.warning(this.getClass().getName()+
            //   ": Error creating AstericsLogger: "+e.getMessage());
            System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: "
                    + e.getMessage());
        }
    }

    return logger;
}

From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java

@GET
@RequireAdmin/*from  w w  w.  ja va 2s.co m*/
@APIDescription("Gets Loggers in the system")
@Produces({ MediaType.APPLICATION_JSON })
@DataType(LoggerView.class)
@Path("/loggers")
public List<LoggerView> getLoggers() {
    List<LoggerView> loggers = new ArrayList<>();

    List<String> allLoggers = LogManager.getLoggingMXBean().getLoggerNames();
    Collections.sort(allLoggers);

    for (String name : allLoggers) {
        LoggerView loggerView = new LoggerView();
        loggerView.setName(name);

        Level levelLocal = LogManager.getLogManager().getLogger(name).getLevel();
        String levelName = "";
        if (levelLocal != null) {
            levelName = levelLocal.getName();
        }
        loggerView.setLevel(levelName);

        Logger localLogger = LogManager.getLogManager().getLogger(name);
        for (Handler handlerLocal : localLogger.getHandlers()) {
            loggerView.getHandlers()
                    .add(handlerLocal.getClass().getName() + " = " + handlerLocal.getLevel().getName());
        }
        loggers.add(loggerView);
    }

    return loggers;
}

From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java

@PUT
@RequireAdmin//from ww w .j av a2s. c o  m
@APIDescription("Sets logger level")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.WILDCARD })
@DataType(LoggerView.class)
@Path("/logger/{loggername}/level")
public Response updateApplicationProperty(@PathParam("loggername") @RequiredParam String loggername,
        String level) {
    Response response = Response.status(Response.Status.NOT_FOUND).build();
    Logger logger = LogManager.getLogManager().getLogger(loggername);
    if (logger != null) {
        List<String> levels = loadLevels();
        boolean saved = false;
        if (StringUtils.isBlank(level)) {
            logger.setLevel(null);
            saved = true;
        } else {
            if (levels.contains(level)) {
                logger.setLevel(Level.parse(level));
                saved = true;
            } else {
                RestErrorModel restErrorModel = new RestErrorModel();
                restErrorModel.getErrors().put("level", "Log level is not valid. Check level value passed in.");
                response = Response.ok(restErrorModel).build();
            }
        }
        if (saved) {
            LoggerView loggerView = new LoggerView();
            loggerView.setName(loggername);
            loggerView.setLevel(level);
            for (Handler handlerLocal : logger.getHandlers()) {
                loggerView.getHandlers()
                        .add(handlerLocal.getClass().getName() + " = " + handlerLocal.getLevel().getName());
            }
            response = Response.ok(loggerView).build();
        }
    }
    return response;
}

From source file:org.ebayopensource.turmeric.plugins.maven.AbstractTurmericMojo.java

/**
 * Wraps the mojo execute with some behavioral lifecycle.
 *///from w ww .  j  av  a2  s.c om
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {
    getLog().debug("[execute]");
    getLog().info("Using turmeric-maven-plugin version " + getTurmericMavenPluginVersion());

    if (executeSkip()) {
        getLog().warn("Skipping execution");
        return;
    }

    if (verbose) {
        logDependencyDetails("Turmeric Maven Plugin", AbstractTurmericMojo.class, GROUPID_SELF,
                ARTIFACTID_SELF);
        logDependencyDetails("Codegen Tools", NonInteractiveCodeGen.class,
                "org.ebayopensource.turmeric.runtime", "soa-client");
        getLog().info("Verbose Mode: enabling java.util.logging");
        // Initialize java.util.logging (which is present in CodeGen classes)

        Logger root = Logger.getLogger("");

        // Remove old delegates
        for (Handler handler : root.getHandlers()) {
            getLog().info("Removing existing logging handler: " + handler.getClass().getName());
            root.removeHandler(handler);
        }

        // Add our delegate
        root.addHandler(new LogDelegateHandler(getLog()));
    }

    getLog().debug("[onValidateParameters]");
    onValidateParameters();

    // Test for need to generate
    getLog().debug("[needsGeneration]");
    if (needsGeneration() == false) {
        getLog().warn("No need to generate. skipping turmeric plugin execution.");
        return;
    }

    try {
        getLog().debug("[onRunSetup]");
        onRunSetup();

        // Attach directories to project even if skipping servicegen.
        // This is to be a good maven and m2eclipse citizen.
        getLog().debug("[onAttachGeneratedDirectories]");
        onAttachGeneratedDirectories();

        getLog().debug("[onRun]");
        onRun();
    } finally {
        getLog().debug("[onRunTearDown]");
        onRunTearDown();
    }
}

From source file:org.silverpeas.core.test.rule.CommonAPI4Test.java

private void setLoggerHandler(final Handler handler) {
    Logger.getLogger(ROOT_NAMESPACE).setUseParentHandlers(false);
    if (Arrays.stream(Logger.getLogger(ROOT_NAMESPACE).getHandlers())
            .filter(h -> handler.getClass().isInstance(h)).count() == 0) {
        Logger.getLogger(ROOT_NAMESPACE).addHandler(handler);
    }//from  w  ww  . j a v  a2 s . c o m
}

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

public static void initLogging(BuildInfo binfo, Class init) {
    try {/*  ww  w  .  j av  a 2  s  .  co m*/
        //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);
    }
}