Example usage for java.util.logging Level getName

List of usage examples for java.util.logging Level getName

Introduction

In this page you can find the example usage for java.util.logging Level getName.

Prototype

public String getName() 

Source Link

Document

Return the non-localized string name of the Level.

Usage

From source file:org.jboss.as.logging.LoggingOperationsSubsystemTestCase.java

private void testChangeRootLogLevel(final String loggingProfile) throws Exception {
    final KernelServices kernelServices = boot();
    final String fileHandlerName = "test-file-handler";

    // add new file logger so we can track logged messages
    final File logFile = createLogFile();
    addFileHandler(kernelServices, loggingProfile, fileHandlerName, org.jboss.logmanager.Level.TRACE, logFile,
            true);//from  ww w  .ja va2s  . c om

    final Level[] levels = { org.jboss.logmanager.Level.FATAL, org.jboss.logmanager.Level.ERROR,
            org.jboss.logmanager.Level.WARN, org.jboss.logmanager.Level.INFO, org.jboss.logmanager.Level.DEBUG,
            org.jboss.logmanager.Level.TRACE };
    final Map<Level, Integer> levelOrd = new HashMap<Level, Integer>();
    levelOrd.put(org.jboss.logmanager.Level.FATAL, 0);
    levelOrd.put(org.jboss.logmanager.Level.ERROR, 1);
    levelOrd.put(org.jboss.logmanager.Level.WARN, 2);
    levelOrd.put(org.jboss.logmanager.Level.INFO, 3);
    levelOrd.put(org.jboss.logmanager.Level.DEBUG, 4);
    levelOrd.put(org.jboss.logmanager.Level.TRACE, 5);

    // log messages on all levels with different root logger level settings
    final ModelNode address = createRootLoggerAddress(loggingProfile).toModelNode();
    for (Level level : levels) {
        // change root log level
        final ModelNode op = SubsystemOperations.createWriteAttributeOperation(address, CommonAttributes.LEVEL,
                level.getName());
        executeOperation(kernelServices, op);
        doLog(loggingProfile, levels, "RootLoggerTestCaseTST %s", level);
    }

    // Remove the handler
    removeFileHandler(kernelServices, loggingProfile, fileHandlerName, true);

    // go through logged messages - test that with each root logger level settings
    // message with equal priority and also messages with all higher
    // priorities were logged

    final boolean[][] logFound = new boolean[levelOrd.size()][levelOrd.size()];

    final List<String> logLines = FileUtils.readLines(logFile);
    for (String line : logLines) {
        if (!line.contains("RootLoggerTestCaseTST"))
            continue; // not our log
        final String[] words = line.split("\\s+");
        try {
            final Level lineLogLevel = Level.parse(words[1]);
            final Level rootLogLevel = Level.parse(words[5]);
            final int producedLevel = levelOrd.get(lineLogLevel);
            final int loggedLevel = levelOrd.get(rootLogLevel);
            assertTrue(String.format("Produced level(%s) greater than logged level (%s)", lineLogLevel,
                    rootLogLevel), producedLevel <= loggedLevel);
            logFound[producedLevel][loggedLevel] = true;
        } catch (Exception e) {
            throw new Exception("Unexpected log:" + line);
        }
    }
    for (Level level : levels) {
        final int rl = levelOrd.get(level);
        for (int ll = 0; ll <= rl; ll++)
            assertTrue(logFound[ll][rl]);
    }

}

From source file:org.jboss.as.logging.LoggingOperationsSubsystemTestCase.java

private ModelNode addFileHandler(final KernelServices kernelServices, final String loggingProfile,
        final String name, final Level level, final File file, final boolean assign) throws Exception {
    final ModelNode address = createFileHandlerAddress(loggingProfile, name).toModelNode();

    // add file handler
    ModelNode op = SubsystemOperations.createAddOperation(address);
    op.get(CommonAttributes.NAME.getName()).set(name);
    op.get(CommonAttributes.LEVEL.getName()).set(level.getName());
    op.get(CommonAttributes.FILE.getName()).get(PathResourceDefinition.PATH.getName())
            .set(file.getAbsolutePath());
    op.get(CommonAttributes.AUTOFLUSH.getName()).set(true);
    executeOperation(kernelServices, op);

    // register it with root logger
    if (assign) {
        op = SubsystemOperations.createOperation(
                RootLoggerResourceDefinition.ROOT_LOGGER_ADD_HANDLER_OPERATION_NAME,
                createRootLoggerAddress(loggingProfile).toModelNode());
        op.get(CommonAttributes.NAME.getName()).set(name);
        executeOperation(kernelServices, op);
    }// w w  w .j  a va 2 s.c  o  m
    return address;
}

From source file:com.vaadin.tests.tb3.AbstractTB3Test.java

protected void assertNoDebugMessage(Level level) {
    // class="v-debugwindow-row Level.getName()"
    List<WebElement> logElements = driver.findElements(By.xpath(String.format(
            "//div[@class='v-debugwindow-row %s']/span[@class='v-debugwindow-message']", level.getName())));
    if (!logElements.isEmpty()) {
        String logRows = "";
        for (WebElement e : logElements) {
            logRows += "\n" + e.getText();
        }/*from  ww  w . ja va2  s. com*/
        Assert.fail("Found debug messages with level " + level.getName() + ": " + logRows);
    }
}

From source file:net.larry1123.elec.util.logger.EELogger.java

/**
 * Will Log a StackTrace and Post it on to http://paste.larry1123.net/
 * Will return true if it was able to post and false if it was not able to post
 * Throws with the Level given//from   ww w . j  a  va2  s .c  om
 *
 * @param lvl     The Level to be thrown with
 * @param message Message to be Logged
 * @param thrown  Throwable Error To be logged
 *
 * @return {@code true} if paste was made of stackTrace; {@code falase} if it failed for any reason
 */
public boolean logStackTraceToPasteBin(Level lvl, String message, Throwable thrown) {
    if (getConfig().isPastingAllowed()) {
        EELogger eeLogger = FactoryManager.getFactoryManager().getEELoggerFactory().getSubLogger("EEUtil",
                "PasteBinLog");
        try {
            URL url = new URL("https://paste.larry1123.net/api/xml/create");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            String urlParameters = "data=" + "[" + lvl.getName() + "] " + message + "\n"
                    + org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(thrown);
            urlParameters += "&";
            String title = "[" + lvl.getName() + "] " + message;
            urlParameters += "title=" + (title.length() > 30 ? title.substring(0, 30) : title);
            urlParameters += "&";
            urlParameters += "language=Java";

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            if (con.getResponseCode() == 200) {
                DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                Document document = dBuilder.parse(con.getInputStream());
                document.getDocumentElement().normalize();

                NodeList nodeList = document.getElementsByTagName("id");
                Node node = nodeList.item(0);
                String id = node.getTextContent();
                eeLogger.info("Logger " + getName() + ": https://paste.larry1123.net/" + id);
                return true;
            }
            return false;
        } catch (MalformedURLException e) {
            eeLogger.error("Failed to send: Malformed", e);
            return false;
        } catch (IOException e) {
            eeLogger.error("Failed to send: IOException", e);
            return false;
        } catch (ParserConfigurationException e) {
            eeLogger.error("Failed to send: ParserConfigurationException", e);
            return false;
        } catch (SAXException e) {
            eeLogger.error("Failed to send: SAXException", e);
            return false;
        }
    } else {
        return false;
    }
}

From source file:contestTabulation.Main.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    final long startTimeMillis = System.currentTimeMillis();
    final Map<Test, Pair<Integer, Integer>> testsGraded = new HashMap<Test, Pair<Integer, Integer>>();
    final List<Test> tiesBroken = new ArrayList<Test>();

    final Entity contestInfo;
    final Map<String, Integer> awardCriteria;

    final Map<Level, Set<Student>> students = new HashMap<Level, Set<Student>>();
    final Map<Level, Map<String, School>> schools = new HashMap<Level, Map<String, School>>();
    final Map<Level, Map<Test, List<Student>>> categoryWinners = new HashMap<Level, Map<Test, List<Student>>>();
    final Map<Level, Map<Subject, List<School>>> categorySweepstakesWinners = new HashMap<Level, Map<Subject, List<School>>>();
    final Map<Level, List<School>> sweepstakesWinners = new HashMap<Level, List<School>>();

    final StringBuilder errorLog = new StringBuilder();

    memCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(java.util.logging.Level.INFO));
    memCache.put("tabulationTaskStatus", ("Running/Init_" + System.currentTimeMillis()).getBytes());

    try {//from w w  w . jav a 2  s.  co  m
        // Retrieve contest information from Datastore
        contestInfo = Retrieve.contestInfo();

        // Get award criteria from Datastore
        awardCriteria = Retrieve.awardCriteria(contestInfo);

        // Initialize data structures
        for (Level level : Level.values()) {
            students.put(level, new HashSet<Student>());
            schools.put(level, new HashMap<String, School>());
            categoryWinners.put(level, new HashMap<Test, List<Student>>());
            categorySweepstakesWinners.put(level, new HashMap<Subject, List<School>>());
            sweepstakesWinners.put(level, new ArrayList<School>());
        }

        // Authenticate to Google Documents Service using OAuth 2.0 Authentication Token from Datastore
        Map<String, String[]> params = req.getParameterMap();
        SpreadsheetService service = new SpreadsheetService("contestTabulation");
        authService(service, contestInfo);

        // Retrieve enabled levels from Datastore
        String[] stringLevels = ((String) contestInfo.getProperty("levels")).split(Pattern.quote("+"));
        Level[] levels = new Level[stringLevels.length];
        for (int i = 0; i < stringLevels.length; i++) {
            levels[i] = Level.fromString(stringLevels[i]);
        }

        for (Level level : levels) {
            memCache.put("tabulationTaskStatus",
                    ("Running/" + level.getName() + "_" + System.currentTimeMillis()).getBytes());
            Map<String, School> lSchools = schools.get(level);
            List<School> lsweepstakesWinners = sweepstakesWinners.get(level);
            Map<Test, List<Student>> lCategoryWinners = categoryWinners.get(level);
            Map<Subject, List<School>> lCategorySweepstakesWinners = categorySweepstakesWinners.get(level);

            // Populate base data structures by traversing Google Documents Spreadsheets
            SpreadsheetEntry spreadsheet = getSpreadSheet(params.get("doc" + level.getName())[0], service);
            Map<String, String> schoolGroups = getSchoolGroups(level, contestInfo);
            updateDatabase(level, spreadsheet, students.get(level), lSchools, schoolGroups, testsGraded,
                    service, errorLog);

            // Populate category winners lists with top scorers (as defined by award criteria)
            tabulateCategoryWinners(level, students.get(level), lCategoryWinners, testsGraded, tiesBroken,
                    awardCriteria, errorLog);

            // Calculate school sweepstakes scores and number of tests fields
            for (School school : lSchools.values()) {
                school.calculateScores();
                school.calculateTestNums();
            }

            // Populate category sweepstakes winners maps and sweepstakes winners lists with top scorers
            tabulateCategorySweepstakesWinners(lSchools, lCategorySweepstakesWinners);
            tabulateSweepstakesWinners(lSchools, lsweepstakesWinners);

            // Persist JDOs in Datastore
            persistData(level, lSchools.values(), lCategoryWinners, lCategorySweepstakesWinners,
                    lsweepstakesWinners);

            // Update Datastore by modifying registrations to include actual number of tests taken
            updateRegistrations(level, lSchools);
        }

        // Update Datastore by modifying contest information entity to include tests graded, last updated timestamp and error logs
        updateContestInfo(testsGraded, tiesBroken, contestInfo, errorLog);

        long elapsedSeconds = TimeUnit.SECONDS.convert(System.currentTimeMillis() - startTimeMillis,
                TimeUnit.MILLISECONDS);
        memCache.put("tabulationTaskStatus", ("Success/" + elapsedSeconds + " second"
                + (elapsedSeconds == 1 ? "" : "s") + "_" + System.currentTimeMillis()).getBytes());
    } catch (Exception e) {
        e.printStackTrace();
        memCache.put("tabulationTaskStatus",
                ("Failed/" + e.getClass().getName() + "_" + System.currentTimeMillis()).getBytes());
    }
}

From source file:com.sun.honeycomb.adm.client.AdminClientImpl.java

public void extLog(Level level, String msgKey, Object[] params, String methodName) {
    String msg = "";
    BigInteger retVal = null;/*from   w ww . j  a  va 2s .c o m*/
    if (!ExtLevel.isExtLevel(level)) {
        logger.warning("Invalid External Audit Log Level: " + level.getName() + "  setting level to: "
                + ExtLevel.EXT_INFO.getName());
        level = ExtLevel.EXT_INFO;
    }
    try {
        // Since only have one session at a time should be able
        // to get locale and resource bundle at login time.
        Locale locale = new Locale(getLocale());
        ResourceBundle bundle = ResourceBundle.getBundle(AdminResourcesConstants.RESOURCE_BUNDLE_NAME, locale);
        String pattern = bundle.getString(msgKey);
        msg = MessageFormat.format(pattern, params);
    } catch (Exception ex) {
        String tmpMsg = "Message not logged." + " Message lookup or message formatting failed."
                + "  Message key: " + msgKey + "  Message String: " + msg;
        logger.logp(Level.WARNING, AdminClientImpl.class.getName(), "extLog", tmpMsg, ex);
        return;
    }

    try {
        if (auditLogger == null) {
            getAuditLogger();
        }
        retVal = auditLogger.logExt(level.getName(), msg, this.classFullname, methodName);
    } catch (Exception ex) {
        String tmpMsg = "Unexpected error. Message not logged to external" + " logger: " + msg;
        logger.logp(Level.WARNING, AdminClientImpl.class.getName(), "extLog", tmpMsg, ex);
        return;
    }
}