Example usage for java.util.logging LogRecord getLevel

List of usage examples for java.util.logging LogRecord getLevel

Introduction

In this page you can find the example usage for java.util.logging LogRecord getLevel.

Prototype

public Level getLevel() 

Source Link

Document

Get the logging message level, for example Level.SEVERE.

Usage

From source file:org.hillview.utils.HillviewLogger.java

/**
 * Create a Hillview logger.//ww w  .ja v a  2s .c o  m
 * @param role      Who is doing the logging: web server, worker, test, etc.
 * @param filename  File where logs are to be written.  If null logs will be written to the
 *                  console.
 */
private HillviewLogger(String role, @Nullable String filename) {
    // Disable all default logging
    LogManager.getLogManager().reset();
    this.logger = Logger.getLogger("Hillview");
    this.machine = this.checkCommas(Utilities.getHostName());
    this.role = this.checkCommas(role);
    this.logger.setLevel(Level.INFO);

    Formatter form = new SimpleFormatter() {
        final String[] components = new String[5];
        final String newline = System.lineSeparator();
        private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

        @Override
        public synchronized String format(LogRecord record) {
            this.components[0] = HillviewLogger.this.checkCommas(df.format(new Date(record.getMillis())));
            this.components[1] = HillviewLogger.this.role;
            this.components[2] = HillviewLogger.this.checkCommas(record.getLevel().toString());
            this.components[3] = HillviewLogger.this.machine;
            this.components[4] = record.getMessage();
            String result = String.join(",", components);
            return result + this.newline;
        }
    };

    Handler handler;
    if (filename != null) {
        try {
            handler = new FileHandler(filename);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        handler = new ConsoleHandler();
    }
    handler.setFormatter(form);
    logger.addHandler(handler);
    File currentDirectory = new File(new File(".").getAbsolutePath());
    this.info("Starting logger", "Working directory: {0}", currentDirectory);
}

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 ww. j  av a  2  s.co  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:org.spoutcraft.launcher.Main.java

@Override
public String format(LogRecord record) {
    StringBuilder builder = new StringBuilder();

    builder.append(date.format(record.getMillis()));
    builder.append(" [");
    builder.append(record.getLevel().getLocalizedName().toUpperCase());
    builder.append("] ");
    builder.append(formatMessage(record));
    builder.append('\n');

    if (record.getThrown() != null) {
        StringWriter writer = new StringWriter();
        record.getThrown().printStackTrace(new PrintWriter(writer));
        builder.append(writer.toString());
    }/* ww w  .  j a  v a2s.  c om*/

    return builder.toString();
}

From source file:pcgen.persistence.lst.DataLoadTest.java

/**
 * Test the load of the current source./*  ww  w  . ja v  a 2  s  .c o  m*/
 * This will check for any load errors or warnings but ignores deprecation warnings.
 */
@Test
public void testLoadSources() {
    UIDelegate uiDelegate = new MockUIDelegate();

    SourceFileLoader loader = new SourceFileLoader(sourceSelection, uiDelegate);
    errors = new ArrayList<>();
    loader.addPCGenTaskListener(this);
    loader.execute();
    GameMode selectedGame = SystemCollections.getGameModeNamed(sourceSelection.getGameMode().get().getName());
    selectedGame.clearLoadContext();
    loader = null;

    List<String> errorList = new ArrayList<>();
    List<String> warningList = new ArrayList<>();
    for (LogRecord logRecord : errors) {
        if (logRecord.getLevel().intValue() > Logging.WARNING.intValue()) {
            errorList.add(logRecord.getMessage());
        } else if (logRecord.getLevel().intValue() > Logging.INFO.intValue()) {
            warningList.add(logRecord.getMessage());
        }
    }
    assertEquals("Errors encountered while loading " + sourceSelection, "", StringUtils.join(errorList, ",\n"));
    assertEquals("Warnings encountered while loading " + sourceSelection, "",
            StringUtils.join(errorList, ",\n"));
}

From source file:pl.otros.logview.logging.GuiJulHandler.java

protected boolean isIgnoringLogRecord(LogRecord record) {
    if (record.getLevel().intValue() < Level.INFO.intValue()) {
        for (String ignoreClass : ignoreClassesList) {
            if (StringUtils.equals(ignoreClass, record.getSourceClassName())) {
                return true;
            }//from  ww w. j  a  v  a 2s .  c om
        }
    }

    return false;
}

From source file:pl.otros.logview.logging.GuiJulHandler.java

@Override
public void publish(LogRecord lr) {
    if (isIgnoringLogRecord(lr)) {
        return;//from w w  w. jav  a 2 s . c o m
    }

    LogData ld = new LogData();
    ld.setMessage(lr.getMessage());
    ld.setDate(new Date(lr.getMillis()));
    ld.setFile("Olv-internal");
    ld.setClazz(lr.getSourceClassName());
    ld.setMethod(lr.getSourceMethodName());
    ld.setThread(Integer.toString(lr.getThreadID()));
    ld.setLevel(lr.getLevel());
    if (bufferingLogDataCollectorProxy != null) {
        bufferingLogDataCollectorProxy.add(ld);
    }
}

From source file:simj.util.logging.HTMLFormatter.java

private String getLogEntry(final LogRecord record) {
    StringBuffer buf = new StringBuffer(2048);

    buf.append("<TR>\n");
    buf.append("<TD><DIV ALIGN=\"right\">");
    buf.append(record.getSequenceNumber());
    buf.append("</DIV></TD>");
    buf.append("<TD>");

    // Bold any levels >= INFO, for instance severe error messages.
    if (record.getLevel().intValue() >= Level.INFO.intValue()) {
        buf.append("<b>");

        if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
            buf.append("<i>");
            buf.append(record.getLevel());
            buf.append("</i>");
        } else {/*  w w  w.  j a v a 2  s  .  co m*/
            buf.append(record.getLevel());
        }

        buf.append("</b>");
    } else {
        buf.append(record.getLevel());
    }

    buf.append("</TD>");
    buf.append("<TD>");
    buf.append(record.getMillis());
    buf.append("</TD>");
    buf.append("<TD>");
    buf.append(record.getSourceClassName());
    buf.append("</TD>");
    buf.append("<TD>");
    buf.append(record.getSourceMethodName());
    buf.append("</TD>");
    buf.append("<TD>");
    buf.append("\n</TR>\n");
    buf.append("<TR>\n");
    buf.append("<TD>");
    buf.append("</TD>");
    buf.append("<TD COLSPAN=\"4\">");
    buf.append("<EM>");
    buf.append(cleanUpHTML(formatMessage(record)));
    buf.append("</EM>");
    buf.append("</TD>");
    buf.append("\n</TR>\n");
    buf.append("<TR>");
    buf.append("<TD COLSPAN=\"5\"><HR SIZE=\"1\" NOSHADE></TD>");
    buf.append("</TR>\n\n");

    return buf.toString();
}

From source file:tvbrowser.TVBrowser.java

/**
 * Creates a very simple Formatter for log formatting
 *
 * @return a very simple Formatter for log formatting.
 *//*from   w w  w  .j a  va2s .c o m*/
private static Formatter createFormatter() {
    return new Formatter() {
        public synchronized String format(LogRecord record) {
            StringBuilder sb = new StringBuilder();

            DateFormat mTimeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);

            String message = formatMessage(record);
            sb.append(mTimeFormat.format(new java.util.Date(System.currentTimeMillis())));
            sb.append(' ');
            sb.append(record.getLevel().getLocalizedName());
            sb.append(": ");
            sb.append(message);
            sb.append('\n');
            if (record.getThrown() != null) {
                try {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    record.getThrown().printStackTrace(pw);
                    pw.close();
                    sb.append(sw.toString());
                } catch (Exception ex) {
                    // ignore
                }
            }
            return sb.toString();
        }
    };
}