Java Code Examples for java.util.logging.LogRecord#getMillis()

The following examples show how to use java.util.logging.LogRecord#getMillis() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BriefLogFormatter.java    From RipplePower with Apache License 2.0 7 votes vote down vote up
@Override
public String format(LogRecord logRecord) {
	Object[] arguments = new Object[6];
	arguments[0] = logRecord.getLevel().getName();
	String fullClassName = logRecord.getSourceClassName();
	int lastDot = fullClassName.lastIndexOf('.');
	String className = fullClassName.substring(lastDot + 1);
	arguments[1] = className;
	arguments[2] = logRecord.getSourceMethodName();
	arguments[3] = new Date(logRecord.getMillis());
	arguments[4] = logRecord.getMessage();
	if (logRecord.getThrown() != null) {
		Writer result = new StringWriter();
		logRecord.getThrown().printStackTrace(new PrintWriter(result));
		arguments[5] = result.toString();
	} else {
		arguments[5] = "";
	}

	return messageFormat.format(arguments);
}
 
Example 2
Source File: IdeSnapshot.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
private Integer getLogRecordValue(int sampleIndex) throws IOException {
    long timestamp = getTimestamp(sampleIndex);
    LogRecord rec = xmlLogs.getRecordFor(timestamp / 1000000);
    if (rec != null) {
        long startTime = cpuSnapshot.getStartTime();
        long endTime = getTimestamp(getSamplesCount() - 1);
        long recTime = rec.getMillis() * 1000000;
        if (recTime > startTime && recTime < endTime) {
            if (rec != lastRecord) {
                Integer index = new Integer(sampleIndex+1);
                lastRecord = rec;
                recordsMap.put(index, rec);
                return index;
            }
        }
    }
    return null;
}
 
Example 3
Source File: PatternFormatter.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void formatImpl(StringBuilder sb, LogRecord log)
{
  long now = log.getMillis();
  
  if (CurrentTime.isTest()) {
    now = CurrentTime.currentTime();
  }
  
  /*
  LocalDateTime time = LocalDateTime.ofEpochSecond(now / 1000, 
                                                   (int) (now % 1000) * 1000000, 
                                                   ZoneOffset.UTC);
                                                   */
  Instant instant = Instant.ofEpochMilli(now);
  ZonedDateTime timeLocal = ZonedDateTime.ofInstant(instant, _localZoneId);
  
  _formatter.format(sb, timeLocal);
}
 
Example 4
Source File: CollectorFormatter.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Updates the summary statistics only if the expected record matches the
 * last record.  The update record is not stored.
 *
 * @param e the LogRecord that is expected.
 * @param u the LogRecord used to collect statistics.
 * @return true if the last record was the expected record.
 * @throws NullPointerException if the update record is null.
 */
private synchronized boolean accept(final LogRecord e, final LogRecord u) {
    /**
     * LogRecord methods must be called before the check of the last stored
     * record to guard against subclasses of LogRecord that might attempt to
     * reset the state by triggering a call to getTail.
     */
    final long millis = u.getMillis(); //Null check.
    final Throwable ex = u.getThrown();
    if (last == e) {  //Only if the exact same reference.
        if (++count != 1L) {
            minMillis = Math.min(minMillis, millis);
        } else { //Show single records as instant and not a time period.
            minMillis = millis;
        }
        maxMillis = Math.max(maxMillis, millis);

        if (ex != null) {
            ++thrown;
        }
        return true;
    } else {
        return false;
    }
}
 
Example 5
Source File: IdeSnapshot.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Integer getLogRecordValue(int sampleIndex) throws IOException {
    long timestamp = getTimestamp(sampleIndex);
    LogRecord rec = xmlLogs.getRecordFor(timestamp / 1000000);
    if (rec != null) {
        long startTime = cpuSnapshot.getStartTime();
        long endTime = getTimestamp(getSamplesCount() - 1);
        long recTime = rec.getMillis() * 1000000;
        if (recTime > startTime && recTime < endTime) {
            if (rec != lastRecord) {
                Integer index = new Integer(sampleIndex+1);
                lastRecord = rec;
                recordsMap.put(index, rec);
                return index;
            }
        }
    }
    return null;
}
 
Example 6
Source File: VisageFormatter.java    From Visage with MIT License 5 votes vote down vote up
@Override
public String format(LogRecord record) {
	if (record.getThrown() != null) {
		record.getThrown().printStackTrace();
	}
	Ansi ansi = Ansi.ansi();
	if (Visage.ansi) {
		ansi.fgBright(Color.BLACK);
	}
	Date date = new Date(record.getMillis());
	ansi.a("@");
	ansi.a(format.format(date));
	if (Visage.ansi) {
		ansi.reset();
	}
	ansi.a(Strings.padStart(Thread.currentThread().getName(), 22, ' '));
	ansi.a(" ");
	if (Visage.ansi && colors.containsKey(record.getLevel())) {
		ansi.fgBright(colors.get(record.getLevel()));
	}
	ansi.a(names.get(record.getLevel()));
	if (Visage.ansi) {
		ansi.reset();
	}
	ansi.a(": ");
	if (Visage.ansi && colors.containsKey(record.getLevel()) && record.getLevel().intValue() >= Level.SEVERE.intValue()) {
		ansi.bold();
		ansi.fgBright(colors.get(record.getLevel()));
	}
	ansi.a(record.getMessage());
	if (Visage.ansi) {
		ansi.reset();
	}
	ansi.a("\n");
	return ansi.toString();
}
 
Example 7
Source File: JSONFormatter.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@Override
public String format(final LogRecord record) {
	try {
		startObject();

		startProperty("level");
		out(record.getLevel().getName());
		endProperty();

		startProperty("message");
		out(record.getMessage());
		endProperty();

		startProperty("event");
		out(record.getSourceClassName() + "." + record.getSourceMethodName() + "()");
		endProperty();

		startProperty("time");
		out(record.getMillis());
		endProperty();

		startProperty("datetime");
		Date recordDate = new Date(record.getMillis());
		out(LogUtils.dateToString(recordDate, UTC_Format));
		endProperty();

		formatThrowable(record);
		endObject();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return _builder.toString();
}
 
Example 8
Source File: ConsoleFormatter.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
public String format(LogRecord record) {

    StringBuilder output = new StringBuilder(512);
    Date eventTime = new Date(record.getMillis());

    output.append("[");
    output.append(format.format(eventTime));
    output.append('|');
    output.append(record.getLevel());
    output.append('|');
    output.append(record.getLoggerName());
    output.append("]: ");
    output.append(record.getMessage());

    if (record.getThrown() != null) {
      output.append("(");
      output.append(record.getThrown().toString());

      Object[] stackTrace = record.getThrown().getStackTrace();
      if (stackTrace.length > 0) {
        output.append("@");
        output.append(stackTrace[0].toString());
      }

      output.append(")");
    }

    output.append(lineSep);

    return output.toString();
  }
 
Example 9
Source File: ConsoleLoggingFormatter.java    From old-mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public String format(LogRecord record) {

    String loggerNameElements[] = record.getLoggerName().split("\\.");
    String loggerName = loggerNameElements[loggerNameElements.length - 1];

    StringBuilder output = new StringBuilder(512);
    Date eventTime = new Date(record.getMillis());

    output.append("[");
    output.append(format.format(eventTime));
    output.append('|');
    output.append(record.getLevel());
    output.append('|');
    output.append(loggerName);
    output.append("]: ");
    output.append(record.getMessage());

    if (record.getThrown() != null) {
      output.append("(");
      output.append(record.getThrown().toString());

      Object[] stackTrace = record.getThrown().getStackTrace();
      if (stackTrace.length > 0) {
        output.append("@");
        output.append(stackTrace[0].toString());
      }

      output.append(")");
    }

    output.append(lineSep);

    return output.toString();
  }
 
Example 10
Source File: MyLogFormatter.java    From kylin with Apache License 2.0 5 votes vote down vote up
/**
 * Format the given LogRecord.
 * 
 * @param record
 *            the log record to be formatted.
 * @return a formatted log record
 */
public synchronized String format(LogRecord record) {
    StringBuffer sb = new StringBuffer();
    // Minimize memory allocations here.
    Timestamp ts = new Timestamp(record.getMillis());
    String text = ts.toString();
    sb.append("JUL ");
    sb.append(text);
    sb.append(" ");
    if (record.getSourceClassName() != null) {
        sb.append(record.getSourceClassName());
    } else {
        sb.append(record.getLoggerName());
    }
    if (record.getSourceMethodName() != null) {
        sb.append(" ");
        sb.append(record.getSourceMethodName());
    }
    sb.append(lineSeparator);
    String message = formatMessage(record);
    sb.append(record.getLevel().getLocalizedName());
    sb.append(": ");
    sb.append(message);
    sb.append(lineSeparator);
    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) {
            //do nothing?
        }
    }
    return sb.toString();
}
 
Example 11
Source File: MyLogFormatter.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
/**
 * Format the given LogRecord.
 * 
 * @param record
 *            the log record to be formatted.
 * @return a formatted log record
 */
public synchronized String format(LogRecord record) {
    StringBuffer sb = new StringBuffer();
    // Minimize memory allocations here.
    Timestamp ts = new Timestamp(record.getMillis());
    String text = ts.toString();
    sb.append("JUL ");
    sb.append(text);
    sb.append(" ");
    if (record.getSourceClassName() != null) {
        sb.append(record.getSourceClassName());
    } else {
        sb.append(record.getLoggerName());
    }
    if (record.getSourceMethodName() != null) {
        sb.append(" ");
        sb.append(record.getSourceMethodName());
    }
    sb.append(lineSeparator);
    String message = formatMessage(record);
    sb.append(record.getLevel().getLocalizedName());
    sb.append(": ");
    sb.append(message);
    sb.append(lineSeparator);
    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) {
            //do nothing?
        }
    }
    return sb.toString();
}
 
Example 12
Source File: OldLogRecordTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testGetSetTimeCheck() {
    long before = lr.getMillis();
    try {
        Thread.sleep(2);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    LogRecord lr2 = new LogRecord(Level.CONFIG, "MSG2");
    long after = lr2.getMillis();
    assertTrue(after-before>0);
}
 
Example 13
Source File: DateFileLogHandler.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private boolean shouldRotate(LogRecord record) {
    if (endDate <= record.getMillis() || !logFileExits()) {
        return true;
    }
    return false;
}
 
Example 14
Source File: UIMALogFormatter.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public synchronized String format(LogRecord record) {
  // if record is null, return an empty String
  if (record == null) {
    return "";
  }

  StringBuffer buffer = new StringBuffer(100);

  // create timestamp
  Date timestamp = new Date(record.getMillis());
  String timestampStr = tsFormatter.format(timestamp);
  // append timestamp to the output string
  buffer.append(timestampStr);

  // append source thread ID
  buffer.append(" - ");
  buffer.append(record.getThreadID());

  // append source class if logrb() method was used, otherwise append logger name
  buffer.append(": ");
  if (record.getSourceClassName() == null || record.getSourceClassName().equals("")) {
    buffer.append(record.getLoggerName());
  } else {
    buffer.append(record.getSourceClassName());
  }

  // append source method if logrb() was used
  if (record.getSourceMethodName() != null) {
    buffer.append('.');
    buffer.append(record.getSourceMethodName());
  }

  // append message level
  buffer.append(": ");
  buffer.append(record.getLevel().getLocalizedName());

  // append message
  buffer.append(": ");
  buffer.append(record.getMessage());

  // append exception if avaialble
  if (record.getThrown() != null) {
    buffer.append(CRLF);
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    record.getThrown().printStackTrace(printWriter);
    printWriter.close();
    buffer.append(stringWriter.toString());
  }

  // append new line at the end
  buffer.append(CRLF);

  // return log entry
  return buffer.toString();
}
 
Example 15
Source File: XmlFormatterNanos.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void test(Properties props) {
    Configuration conf = Configuration.apply(props);

    LogRecord record = new LogRecord(Level.INFO, "Test Name: {0}");
    record.setLoggerName("test");
    record.setParameters(new Object[] {conf.testName()});
    int nanos = record.getInstant().getNano() % NANOS_IN_MILLI;
    long millis = record.getMillis();
    // make sure we don't have leading zeros when printing below
    // the second precision
    if (millis % MILLIS_IN_SECOND < 100) millis = millis + 100;
    // make sure we some nanos - and make sure we don't have
    // trailing zeros
    if (nanos % 10 == 0) nanos = nanos + 7;

    record.setMillis(millis);
    setNanoAdjustment(record, nanos);
    final Instant instant = record.getInstant();
    if (nanos < 0) {
        throw new RuntimeException("Unexpected negative nano adjustment: "
                + getNanoAdjustment(record));
    }
    if (nanos >= NANOS_IN_MILLI) {
        throw new RuntimeException("Nano adjustment exceeds 1ms: "
                + getNanoAdjustment(record));
    }
    if (millis != record.getMillis()) {
        throw new RuntimeException("Unexpected millis: " + millis + " != "
                + record.getMillis());
    }
    if (millis != record.getInstant().toEpochMilli()) {
        throw new RuntimeException("Unexpected millis: "
                + record.getInstant().toEpochMilli());
    }
    long expectedNanos = (millis % MILLIS_IN_SECOND) * NANOS_IN_MILLI + nanos;
    assertEquals(expectedNanos, instant.getNano(), "Instant.getNano()");

    XMLFormatter formatter = new XMLFormatter();
    testMatching(formatter, record, instant, expectedNanos, conf.useInstant(formatter));

    XMLFormatter custom = new CustomXMLFormatter();
    testMatching(custom, record, instant, expectedNanos, conf.useInstant(custom));
}
 
Example 16
Source File: SimpleFormatterNanos.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Locale.setDefault(Locale.ENGLISH);
        LogRecord record = new LogRecord(Level.INFO, "Java Version: {0}");
        record.setLoggerName("test");
        record.setParameters(new Object[] {System.getProperty("java.version")});
        int nanos = getNanoAdjustment(record);
        long millis = record.getMillis();
        // make sure we don't have leading zeros when printing below
        // the second precision
        if (millis % MILLIS_IN_SECOND < 100) millis = millis + 100;
        // make sure we have some nanos
        if (nanos % NANOS_IN_MICRO == 0) nanos = nanos + 999;
        record.setMillis(millis);
        setNanoAdjustment(record, nanos);
        final Instant instant = record.getInstant();
        if (nanos < 0) {
            throw new RuntimeException("Unexpected negative nano adjustment: "
                    + getNanoAdjustment(record));
        }
        if (nanos >= NANOS_IN_MILLI) {
            throw new RuntimeException("Nano adjustment exceeds 1ms: "
                    + getNanoAdjustment(record));
        }
        if (millis != record.getMillis()) {
            throw new RuntimeException("Unexpected millis: " + millis + " != "
                    + record.getMillis());
        }
        if (millis != record.getInstant().toEpochMilli()) {
            throw new RuntimeException("Unexpected millis: "
                    + record.getInstant().toEpochMilli());
        }
        ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
        int zdtNanos = zdt.getNano();
        long expectedNanos = (millis % MILLIS_IN_SECOND) * NANOS_IN_MILLI + nanos;
        assertEquals(expectedNanos, instant.getNano(), "Instant.getNano()");
        assertEquals(expectedNanos, zdtNanos, "ZonedDateTime.getNano()");
        String match = "."+expectedNanos+" ";

        System.out.println("Testing with default format...");

        SimpleFormatter formatter = new SimpleFormatter();
        String str = formatter.format(record);
        if (str.contains(match)) {
            throw new RuntimeException("SimpleFormatter.format()"
                    + " string contains unexpected nanos: "
                    + "\n\tdid not expect match for: '" + match + "'"
                    + "\n\tin: " + str);
        }

        System.out.println("Nanos omitted as expected: no '"+match+"' in "+str);


        System.out.println("Changing format to print nanos...");
        System.setProperty("java.util.logging.SimpleFormatter.format",
                "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS.%1$tN %1$Tp %2$s%n%4$s: %5$s%6$s%n");

        SimpleFormatter formatter2 = new SimpleFormatter();
        str = formatter2.format(record);
        if (!str.contains(match)) {
            throw new RuntimeException("SimpleFormatter.format()"
                    + " string does not contain expected nanos: "
                    + "\n\texpected match for: '" + match + "'"
                    + "\n\tin: " + str);
        }
        System.out.println("Found expected match for '"+match+"' in "+str);


        System.out.println("Changing format to omit nanos...");
        System.setProperty("java.util.logging.SimpleFormatter.format",
                "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n");

        SimpleFormatter formatter3 = new SimpleFormatter();
        str = formatter3.format(record);
        String notMatch = match;
        if (str.contains(notMatch)) {
            throw new RuntimeException("SimpleFormatter.format()"
                    + " string contains unexpected nanos: "
                    + "\n\tdid not expect match for: '" + notMatch + "'"
                    + "\n\tin: " + str);
        }
        System.out.println("Nanos omitted as expected: no '"+notMatch+"' in "+str);

    }
 
Example 17
Source File: VmRuntimeLogHandler.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
private ApiProxy.LogRecord convertLogRecord(LogRecord record, String message) {
  ApiProxy.LogRecord.Level level = convertLogLevel(record.getLevel());
  long timestamp = record.getMillis() * 1000;

  return new ApiProxy.LogRecord(level, timestamp, message);
}
 
Example 18
Source File: LogFormatter.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public String format(LogRecord record) {
    return record.getMillis() + " " + record.getLevel() + " "
            + record.getLoggerName().substring(record.getLoggerName().lastIndexOf('.') + 1) + " " + record.getMessage() + "\n";
}
 
Example 19
Source File: JdkLoggerFormatter.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Override
public String format(LogRecord record) {
    Throwable t=record.getThrown();
    int level=record.getLevel().intValue();
    String name=record.getLoggerName();
    long time=record.getMillis();
    String message=formatMessage(record);


    if( name.indexOf('.') >= 0 )
        name = name.substring(name.lastIndexOf('.') + 1);

    // Use a string buffer for better performance
    StringBuilder buf = new StringBuilder();
    
    buf.append(time);
    
    // pad to 8 to make it more readable 
    for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
    
    //      Append a readable representation of the log level.
    switch(level) {
     case LOG_LEVEL_TRACE: buf.append(" T "); break;
     case LOG_LEVEL_DEBUG: buf.append(" D "); break;
     case LOG_LEVEL_INFO:  buf.append(" I ");  break;
     case LOG_LEVEL_WARN:  buf.append(" W ");  break;
     case LOG_LEVEL_ERROR: buf.append(" E "); break;
     //case : buf.append(" F "); break;
     default: buf.append("   ");
     }
     

    // Append the name of the log instance if so configured
    buf.append(name);
    buf.append(" ");

    // pad to 20 chars 
    for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
            
    // Append the message
    buf.append(message);
    
    // Append stack trace if not null
    if(t != null) {
        buf.append(LINE_SEP);
        
        java.io.StringWriter sw= new java.io.StringWriter(1024);
        java.io.PrintWriter pw= new java.io.PrintWriter(sw);
        t.printStackTrace(pw);
        pw.close();
        buf.append(sw.toString());
    }
    
    buf.append(LINE_SEP);
    // Print to the appropriate destination
    return buf.toString();
}
 
Example 20
Source File: JdkLoggerFormatter.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public String format(LogRecord record) {
    Throwable t=record.getThrown();
    int level=record.getLevel().intValue();
    String name=record.getLoggerName();
    long time=record.getMillis();
    String message=formatMessage(record);


    if( name.indexOf('.') >= 0 )
        name = name.substring(name.lastIndexOf('.') + 1);

    // Use a string buffer for better performance
    StringBuilder buf = new StringBuilder();

    buf.append(time);

    // pad to 8 to make it more readable
    for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }

    //      Append a readable representation of the log level.
    switch(level) {
     case LOG_LEVEL_TRACE: buf.append(" T "); break;
     case LOG_LEVEL_DEBUG: buf.append(" D "); break;
     case LOG_LEVEL_INFO:  buf.append(" I ");  break;
     case LOG_LEVEL_WARN:  buf.append(" W ");  break;
     case LOG_LEVEL_ERROR: buf.append(" E "); break;
     //case : buf.append(" F "); break;
     default: buf.append("   ");
     }


    // Append the name of the log instance if so configured
    buf.append(name);
    buf.append(" ");

    // pad to 20 chars
    for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }

    // Append the message
    buf.append(message);

    // Append stack trace if not null
    if(t != null) {
        buf.append(System.lineSeparator());

        java.io.StringWriter sw= new java.io.StringWriter(1024);
        java.io.PrintWriter pw= new java.io.PrintWriter(sw);
        t.printStackTrace(pw);
        pw.close();
        buf.append(sw.toString());
    }

    buf.append(System.lineSeparator());
    // Print to the appropriate destination
    return buf.toString();
}