java.util.logging.LogRecord Java Examples

The following examples show how to use java.util.logging.LogRecord. 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: SimpleLogHandlerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSymbolicLinkInitiallyInvalidReplaced() throws Exception {
  if (OS.getCurrent() == OS.WINDOWS) {
    // On Windows, by default, only administrator accounts can create symbolic links.
    return;
  }
  Path symlinkPath = Paths.get(tmp.getRoot().toString(), "hello");
  Files.createSymbolicLink(symlinkPath, Paths.get("no-such-file"));

  // Expected to delete the (invalid) symlink and replace with a symlink to the log
  SimpleLogHandler handler =
      SimpleLogHandler.builder().setPrefix(symlinkPath.toString()).build();
  handler.publish(new LogRecord(Level.SEVERE, "Hello world")); // To open the log file.

  assertThat(handler.getSymbolicLinkPath().get().toString()).isEqualTo(symlinkPath.toString());
  assertThat(Files.isSymbolicLink(handler.getSymbolicLinkPath().get())).isTrue();
  assertThat(Files.readSymbolicLink(handler.getSymbolicLinkPath().get()).toString())
      .isEqualTo(handler.getCurrentLogFilePath().get().getFileName().toString());
}
 
Example #2
Source File: FolderObj.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void createFolder(final File folder2Create, final String name) throws IOException {
    boolean isSupported = new FileInfo(folder2Create).isSupportedFile();
    ProvidedExtensions extensions =  getProvidedExtensions();

    if (!isSupported) { 
        extensions.createFailure(this, folder2Create.getName(), true);
        FSException.io("EXC_CannotCreateFolder", folder2Create.getName(), getPath());// NOI18N   
    } else if (FileChangedManager.getInstance().exists(folder2Create)) {
        extensions.createFailure(this, folder2Create.getName(), true);            
        SyncFailedException sfe = new SyncFailedException(folder2Create.getAbsolutePath()); // NOI18N               
        String msg = NbBundle.getMessage(FileBasedFileSystem.class, "EXC_CannotCreateFolder", folder2Create.getName(), getPath()); // NOI18N
        Exceptions.attachLocalizedMessage(sfe, msg);
        throw sfe;
    } else if (!folder2Create.mkdirs()) {
        extensions.createFailure(this, folder2Create.getName(), true);
        FSException.io("EXC_CannotCreateFolder", folder2Create.getName(), getPath());// NOI18N               
    }
    LogRecord r = new LogRecord(Level.FINEST, "FolderCreated: "+ folder2Create.getAbsolutePath());
    r.setParameters(new Object[] {folder2Create});
    Logger.getLogger("org.netbeans.modules.masterfs.filebasedfs.fileobjects.FolderObj").log(r);
}
 
Example #3
Source File: StackTraceReportView.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Entry point for creating and display a 'stack trace report' window, a window which provides a
 * basic UI where users can enter an error description before uploading an error report. The
 * window is tied to a stack trace or error that happened and would be uploaded as part of the
 * report. The user description is for developer benefit to get an opportunity for more
 * information around the circumstances of an error.
 */
static void showWindow(
    final Component parentWindow, final ErrorReportClient uploader, final LogRecord logRecord) {

  final StackTraceReportView window = new StackTraceReportSwingView(parentWindow);

  final StackTraceReportModel viewModel =
      StackTraceReportModel.builder()
          .view(window)
          .stackTraceRecord(logRecord)
          .formatter(new StackTraceErrorReportFormatter())
          .uploader(
              ErrorReportUploadAction.builder()
                  .serviceClient(uploader)
                  .successConfirmation(ConfirmationDialogController::showSuccessConfirmation)
                  .failureConfirmation(ConfirmationDialogController::showFailureConfirmation)
                  .build())
          .preview(new ReportPreviewSwingView(parentWindow))
          .build();

  window.bindActions(viewModel);
  window.show();
}
 
Example #4
Source File: AbstractEventLogHandler.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Override
public final void publish(LogRecord record) {
	if (abstractHandler) {
		throw new IllegalArgumentException("May not log to abstract handler");
	}
	if (record instanceof EventLogRecord) {
		try {
			publishEvent((EventLogRecord) record);
		} catch (IOException e) {
			throw new IllegalStateException("Unable to log an event", e);
		}
	} else {
		LOGGER.warn("Unable to Event log an record of class: {}", record.getClass().getCanonicalName());
		throw new IllegalArgumentException("Invalid class for event log: " + record.getClass().getCanonicalName() );
	}
}
 
Example #5
Source File: SingleModuleProperties.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/** Sends info to UI handler about NetBeans APIs in use
 */
private static void logNetBeansAPIUsage(String msg, Collection<ModuleDependency> deps) {
    List<String> cnbs = new ArrayList<String>();
    for (ModuleDependency moduleDependency : deps) {
        String cnb = moduleDependency.getModuleEntry().getCodeNameBase();
        // observe just NetBeans API module usage
        if (cnb.startsWith("org.openide") || cnb.startsWith("org.netbeans")) { // NOI18N
            cnbs.add(cnb);
        }
    }

    if (cnbs.isEmpty()) {
        return;
    }

    LogRecord rec = new LogRecord(Level.CONFIG, msg);
    rec.setParameters(cnbs.toArray(new String[0]));
    rec.setResourceBundleName(SingleModuleProperties.class.getPackage().getName() + ".Bundle"); // NOI18N
    rec.setResourceBundle(NbBundle.getBundle(SingleModuleProperties.class));
    rec.setLoggerName(UI_LOG.getName());
    UI_LOG.log(rec);
}
 
Example #6
Source File: BasicFormatter.java    From nmonvisualizer with Apache License 2.0 6 votes vote down vote up
@Override
public String format(LogRecord record) {
    StringWriter buffer = new StringWriter(256);

    buffer.append(format.format(record.getMillis()));
    buffer.append(" ");
    buffer.append(record.getLevel().getName());
    buffer.append(" ");
    buffer.append(record.getSourceClassName());
    buffer.append(".");
    buffer.append(record.getSourceMethodName());
    buffer.append(": ");
    buffer.append(record.getMessage());
    buffer.append("\n");

    if (record.getThrown() != null) {
        PrintWriter pw = new PrintWriter(buffer);
        record.getThrown().printStackTrace(pw);

        pw.close();
    }
    // else nothing since StringWriter.close() is a no-op

    return buffer.toString();
}
 
Example #7
Source File: DefinitionVerifierTest.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Tests with a CRS having wrong axis order.
 *
 * @throws FactoryException if an error occurred while querying the authority factory.
 */
@Test
@DependsOnMethod("testNormalizedCRS")
public void testDifferentAxisOrder() throws FactoryException {
    final Map<String,Object> properties = new HashMap<>(4);
    properties.put(DefaultGeographicCRS.NAME_KEY, "WGS 84");
    properties.put(DefaultGeographicCRS.IDENTIFIERS_KEY, new NamedIdentifier(HardCodedCitations.EPSG, "4326"));
    DefaultGeographicCRS crs = HardCodedCRS.WGS84;
    crs = new DefaultGeographicCRS(properties, crs.getDatum(), crs.getCoordinateSystem());

    final DefinitionVerifier ver = DefinitionVerifier.withAuthority(crs, null, false);
    assertNotNull("Should replace by normalized CRS", ver);
    assertNotSame("Should replace by normalized CRS", crs, ver.authoritative);
    assertSame   ("Should replace by normalized CRS", CommonCRS.WGS84.normalizedGeographic(), ver.authoritative);

    final LogRecord warning = ver.warning(true);
    assertNotNull("Should emit a warning.", warning);
    final String message = new SimpleFormatter().formatMessage(warning);
    assertTrue(message, message.contains("WGS 84"));
    assertTrue(message, message.contains("EPSG:4326"));
}
 
Example #8
Source File: LeanFormatter.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String format(LogRecord record) {
	StringBuilder b = new StringBuilder();
	b.append(dateFormat.format(new Date(record.getMillis())));
	b.append(" ");
	b.append(record.getLevel().getLocalizedName());
	b.append(": ");
	b.append(formatMessage(record));
	String className = record.getSourceClassName();
	if (className != null) {
		int dot = className.lastIndexOf('.');
		if (dot != -1) {
			className = className.substring(dot + 1);
		}
		b.append(" (").append(className).append(".").append(record.getSourceMethodName()).append("())");
	}
	b.append("\n");
	append(record.getThrown(), b);
	return b.toString();
}
 
Example #9
Source File: JavaLoggingAspect.java    From glowroot with Apache License 2.0 6 votes vote down vote up
private static LogAdviceTraveler onBeforeCommon(ThreadContext context, LogRecord record,
        Level level) {
    // cannot check Logger.getFilter().isLoggable(LogRecord) because the Filter object
    // could be stateful and might alter its state (e.g.
    // com.sun.mail.util.logging.DurationFilter)
    String formattedMessage = nullToEmpty(formatter.formatMessage(record));
    int lvl = level.intValue();
    Throwable t = record.getThrown();
    if (LoggerPlugin.markTraceAsError(lvl >= Level.SEVERE.intValue(),
            lvl >= Level.WARNING.intValue(), t != null)) {
        context.setTransactionError(formattedMessage, t);
    }
    TraceEntry traceEntry =
            context.startTraceEntry(new LogMessageSupplier(level.getName().toLowerCase(),
                    record.getLoggerName(), formattedMessage), timerName);
    return new LogAdviceTraveler(traceEntry, lvl, formattedMessage, t);
}
 
Example #10
Source File: DenominatorD.java    From denominator with Apache License 2.0 6 votes vote down vote up
static void setupLogging() {
  final long start = currentTimeMillis();
  ConsoleHandler handler = new ConsoleHandler();
  handler.setLevel(Level.FINE);
  handler.setFormatter(new Formatter() {
    @Override
    public String format(LogRecord record) {
      return String.format("%7d - %s%n", record.getMillis() - start, record.getMessage());
    }
  });

  Logger[] loggers = {
      Logger.getLogger(DenominatorD.class.getPackage().getName()),
      Logger.getLogger(feign.Logger.class.getName()),
      Logger.getLogger(MockWebServer.class.getName())
  };

  for (Logger logger : loggers) {
    logger.setLevel(Level.FINE);
    logger.setUseParentHandlers(false);
    logger.addHandler(handler);
  }
}
 
Example #11
Source File: StackTraceErrorReportFormatter.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a string formatted in markdown. If we have an exception we'll log the full exception
 * name and stack trace. If there is a log message we will log it, this might be redundant to the
 * exception message (but that is okay!). Otherwise we will log base information like OS, TripleA
 * version and Java version.
 */
private String buildBody(@Nullable final String userDescription, final LogRecord logRecord) {
  return Optional.ofNullable(Strings.emptyToNull(userDescription))
          .map(description -> "## User Description\n" + description + "\n\n")
          .orElse("")
      + Optional.ofNullable(logRecord.getMessage())
          .map(msg -> "## Log Message\n" + msg + "\n\n")
          .orElse("")
      + "## TripleA Version\n"
      + ClientContext.engineVersion()
      + "\n\n"
      + "## Java Version\n"
      + SystemProperties.getJavaVersion()
      + "\n\n"
      + "## Operating System\n"
      + SystemProperties.getOperatingSystem()
      + "\n\n"
      + Optional.ofNullable(logRecord.getThrown())
          .map(StackTraceErrorReportFormatter::throwableToString)
          .orElse("");
}
 
Example #12
Source File: RoboconfLogFormatter.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
@Override
public String format( LogRecord record ) {

	// Center the level
	int totalSpaces = LEVEL_SPAN - record.getLevel().toString().length();
	StringBuilder sbLevel = new StringBuilder();
	for( int i=0; i<totalSpaces/2; i++ )
		sbLevel.append( " " );

	sbLevel.append( record.getLevel());
	for( int i=sbLevel.toString().length(); i<LEVEL_SPAN; i++ )
		sbLevel.append( " " );

	// Format the entire record
	StringBuilder sb = new StringBuilder();
	sb.append( "[ " ).append( this.df.format( new Date( record.getMillis()))).append(" ]" );
	sb.append( "[ ").append( sbLevel ).append( " ] " );
	sb.append( record.getSourceClassName()).append("#");
	sb.append( record.getSourceMethodName());

	sb.append( "\n" );
	sb.append( formatMessage( record ));
	sb.append( "\n" );

	return sb.toString();
}
 
Example #13
Source File: LogcatHandler.java    From slf4android with MIT License 6 votes vote down vote up
@Override
public void publish(LogRecord record) {
    if (!isLoggable(record)) {
        return;
    }
    pl.brightinventions.slf4android.LogRecord slfRecord = pl.brightinventions.slf4android.LogRecord.fromRecord(record);
    int level = slfRecord.getLogLevel().getAndroidLevel();
    String tag = record.getLoggerName();

    try {
        String message = logRecordFormatter.format(slfRecord);
        Log.println(level, tag, message);
    } catch (RuntimeException e) {
        Log.e("LogcatHandler", "Error logging message.", e);
    }
}
 
Example #14
Source File: SerializeLogRecord.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Deserializes the Base64 encoded string returned by {@link
 * #getBase64()}, format the obtained LogRecord using a
 * SimpleFormatter, and checks that the string representation obtained
 * matches the original string representation returned by {@link
 * #getString()}.
 */
protected void dotest() {
    try {
        final String base64 = getBase64();
        final ByteArrayInputStream bais =
                new ByteArrayInputStream(Base64.getDecoder().decode(base64));
        final ObjectInputStream ois = new ObjectInputStream(bais);
        final LogRecord record = (LogRecord)ois.readObject();
        final SimpleFormatter formatter = new SimpleFormatter();
        String expected = getString();
        String str2 = formatter.format(record);
        check(expected, str2);
        System.out.println(str2);
        System.out.println("PASSED: "+this.getClass().getName()+"\n");
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
Example #15
Source File: VespaFormatterTestCase.java    From vespa with Apache License 2.0 6 votes vote down vote up
/**
 * test that {0} etc is replaced properly
 */
@Test
public void testTextFormatting () {
    VespaFormatter formatter = new VespaFormatter(serviceName, app);

    LogRecord testRecord = new LogRecord(Level.INFO, "this {1} is {0} test");
    testRecord.setInstant(Instant.ofEpochMilli(1098709021843L));
    testRecord.setThreadID(123);
    testRecord.setLoggerName("org.foo");
    Object[] params = { "a small", "message" };
    testRecord.setParameters(params);

    String expected = "1098709021.843000\t"
                      + hostname + "\t"
                      + pid
                      + "/123" + "\t"
                      + "serviceName\t"
                      + app
                      + ".org.foo\t"
                      + "info\t"
                      + "this message is a small test\n";

    assertEquals(expected, formatter.format(testRecord));
}
 
Example #16
Source File: VertxLogDelegate.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private void log(Level level, Object message, Throwable t, Object... params) {
    if (!logger.isLoggable(level)) {
        return;
    }
    String msg = (message == null) ? "NULL" : message.toString();
    LogRecord record = new LogRecord(level, msg);
    record.setLoggerName(logger.getName());
    if (t != null) {
        record.setThrown(t);
    } else if (params != null && params.length != 0 && params[params.length - 1] instanceof Throwable) {
        // The exception may be the last parameters (SLF4J uses this convention).
        // As the logger can be used in a SLF4J style, we need to check
        record.setThrown((Throwable) params[params.length - 1]);
    }
    record.setSourceClassName(null);
    record.setParameters(params);
    logger.log(record);
}
 
Example #17
Source File: SimpleLogHandlerTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSymbolicLinkSetter() throws Exception {
  SimpleLogHandler handler =
      SimpleLogHandler.builder()
          .setPrefix(tmp.getRoot() + File.separator + "hello")
          .setSymlinkName("bye")
          .build();
  handler.publish(new LogRecord(Level.SEVERE, "Hello world")); // To open the log file.

  if (OS.getCurrent() == OS.WINDOWS) {
    // On Windows, by default, only administrator accounts can create symbolic links.
    assertThat(handler.getSymbolicLinkPath()).isEmpty();
  } else {
    assertThat(handler.getSymbolicLinkPath()).isPresent();
    assertThat(handler.getSymbolicLinkPath().get().toString())
        .isEqualTo(tmp.getRoot() + File.separator + "bye");
    assertThat(Files.isSymbolicLink(handler.getSymbolicLinkPath().get())).isTrue();
    assertThat(Files.readSymbolicLink(handler.getSymbolicLinkPath().get()).toString())
        .isEqualTo(handler.getCurrentLogFilePath().get().getFileName().toString());
  }
}
 
Example #18
Source File: DetectorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@RandomlyFails
public void testBLE91246() throws Exception {
    final boolean wasThrown[] = new boolean[1];
    Logger.getLogger(Utilities.class.getName()).addHandler(new Handler() {
        public void publish(LogRecord lr) {
            if (lr.getThrown() != null && lr.getThrown().getClass() == BadLocationException.class) {
                wasThrown[0] = true;
            }
        }
        public void close() {}
        public void flush() {}
    });
    performTest("BLE91246");

    assertFalse("BLE was not thrown", wasThrown[0]);
}
 
Example #19
Source File: Slf4jLogTest.java    From mongodb-async-driver with Apache License 2.0 6 votes vote down vote up
/**
 * Test for the {@link AbstractLog#info(String, Object...)} method.
 */
@Test
public void testInfoStringObjectArray() {
    final String method = "testInfoStringObjectArray";
    final String messsage = "Info - Hello {}"; // "Info - Hello World";
    final Level level = Level.INFO;

    myTestLog.info("Info - Hello {}", "World");

    final List<LogRecord> records = myCaptureHandler.getRecords();
    assertThat(records.size(), is(1));

    final LogRecord record = records.get(0);
    assertThat(record.getLevel(), is(level));
    assertThat(record.getLoggerName(), is(Slf4jLogTest.class.getName()));
    assertThat(record.getMessage(), is(messsage));
    assertThat(record.getSourceClassName(),
            is(Slf4jLogTest.class.getName()));
    assertThat(record.getSourceMethodName(), is(method));
    assertThat(record.getThrown(), nullValue());
}
 
Example #20
Source File: JulLogTest.java    From mongodb-async-driver with Apache License 2.0 6 votes vote down vote up
/**
 * Test for the {@link AbstractLog#warn(String)} method.
 */
@Test
public void testWarnString() {
    final String method = "testWarnString";
    final String messsage = "Warning Message";
    final Level level = Level.WARNING;

    myTestLog.warn(messsage);

    final List<LogRecord> records = myCaptureHandler.getRecords();
    assertThat(records.size(), is(1));

    final LogRecord record = records.get(0);
    assertThat(record.getLevel(), is(level));
    assertThat(record.getLoggerName(), is(JulLogTest.class.getName()));
    assertThat(record.getMessage(), is(messsage));
    assertThat(record.getSourceClassName(), is(JulLogTest.class.getName()));
    assertThat(record.getSourceMethodName(), is(method));
    assertThat(record.getThreadID(), is((int) Thread.currentThread()
            .getId()));
    assertThat(record.getThrown(), nullValue());
}
 
Example #21
Source File: PCGenTask.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected void fireErrorOccurredEvent(LogRecord message)
{
	PCGenTaskEvent taskEvent = null;
	// Guaranteed to return a non-null array
	Object[] listeners = listenerList.getListenerList();
	// Process the listeners last to first, notifying
	// those that are interested in this event
	for (int i = listeners.length - 2; i >= 0; i -= 2)
	{
		if (listeners[i] == PCGenTaskListener.class)
		{
			// Lazily create the event:
			if (taskEvent == null)
			{
				taskEvent = new PCGenTaskEvent(this, message);
			}
			((PCGenTaskListener) listeners[i + 1]).errorOccurred(taskEvent);
		}
	}
}
 
Example #22
Source File: LevelHandler.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Publishes the record.
 */
public void publish(LogRecord record)
{
  if (! isLoggable(record))
    return;
  
  int level = getLevel().intValue();

  for (int i = 0; i < _handlers.length; i++) {
    Handler handler = _handlers[i];

    if (level <= handler.getLevel().intValue())
      handler.publish(record);
  }
}
 
Example #23
Source File: DebugLogger.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        @Override
        public Void run() {
            for (final Handler h : logger.getHandlers()) {
                logger.removeHandler(h);
            }

            logger.setLevel(level);
            logger.setUseParentHandlers(false);
            final Handler c = new ConsoleHandler();

            c.setFormatter(new Formatter() {
                @Override
                public String format(final LogRecord record) {
                    final StringBuilder sb = new StringBuilder();

                    sb.append('[')
                    .append(record.getLoggerName())
                    .append("] ")
                    .append(record.getMessage())
                    .append('\n');

                    return sb.toString();
                }
            });
            logger.addHandler(c);
            c.setLevel(level);
            return null;
        }
    }, createLoggerControlAccCtxt());

    return logger;
}
 
Example #24
Source File: DefaultClassPathProviderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void publish(LogRecord record) {
    final String msg = record.getMessage();
    if (msg != null) {
        switch (msg) {
            case "platformCache updated: {0}":
                cachedPlatforms.add((Optional<JavaPlatform>)record.getParameters()[0]);
                break;
            case "lru updated: {0}":
                lru.add((JavaPlatform)record.getParameters()[0]);
                break;
        }
    }
}
 
Example #25
Source File: SerializeLogRecord.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void generate() {
    try {
        LogRecord record = new LogRecord(Level.INFO, "Java Version: {0}");
        record.setLoggerName("test");
        record.setParameters(new Object[] {System.getProperty("java.version")});
        System.out.println(generate(record));
    } catch (IOException | ClassNotFoundException x) {
        throw new RuntimeException(x);
    }
}
 
Example #26
Source File: SimpleLogRecordTest.java    From flogger with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithArgumentsAndMetadata() {
  LogData data =
      FakeLogData.withPrintfStyle("Foo='%s'", "bar")
          .setTimestampNanos(123456789000L)
          .addMetadata(COUNT_KEY, 23)
          .addMetadata(ID_KEY, "test ID");

  LogRecord record = SimpleLogRecord.create(data);

  assertThat(record.getLevel()).isEqualTo(Level.INFO);
  assertThat(record.getMessage()).isEqualTo("Foo='bar' [CONTEXT count=23 id=\"test ID\" ]");
  assertThat(record.getParameters()).isNull();
  // Just do this once for sanity checking - it's only for debugging.
  record.setMillis(123456789);
  assertThat(record.toString())
      .isEqualTo(
          "SimpleLogRecord {\n"
              + "  message: Foo='bar' [CONTEXT count=23 id=\"test ID\" ]\n"
              + "  arguments: <none>\n"
              + "  original message: Foo='%s'\n"
              + "  original arguments:\n"
              + "    bar\n"
              + "  metadata:\n"
              + "    count: 23\n"
              + "    id: test ID\n"
              + "  level: INFO\n"
              + "  timestamp (nanos): 123456789000\n"
              + "  class: com.google.FakeClass\n"
              + "  method: fakeMethod\n"
              + "  line number: 123\n"
              + "}");
}
 
Example #27
Source File: AndroidLogHandler.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
    public void publish(LogRecord record) {

        int level = getAndroidLevel(record.getLevel());
//        String tag = loggerNameToTag(record.getLoggerName());
        String tag = record.getLoggerName();

        try {
            String message = JME_FORMATTER.format(record);
            Log.println(level, tag, message);
        } catch (RuntimeException e) {
            Log.e("AndroidHandler", "Error logging message.", e);
        }
    }
 
Example #28
Source File: PerformanceTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOpenJSP() throws Exception {
    StyledDocument doc = prepare("performance.jsp");
    doc.insertString(0, "${\"hello\"}", null);
    waitTimeout();
    doc.insertString(doc.getEndPosition().getOffset() - 1, "<%= \"hello\" %>", null);
    waitTimeout();
    for (LogRecord log : timerHandler.logs) {
        if (log.getMessage().contains("Navigator Initialization")) {
            verify(log, 500, 2000);
        } else {
            verify(log, 200, 800);
        }
    }
}
 
Example #29
Source File: ApplicationLogHandler.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void publish(LogRecord record) {
    if (record.getLevel().equals(Level.SEVERE)) {
        io.getErr().println(formatter.formatMessage(record));
    }
    else if (record.getLevel().equals(Level.WARNING)) {
        io.getErr().println(formatter.formatMessage(record));
    }
    else {
        io.getOut().println(formatter.formatMessage(record));
    }
}
 
Example #30
Source File: TestLogrbResourceBundle.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void publish(LogRecord record) {
    lastBundle = record.getResourceBundle();
    lastBundleName = record.getResourceBundleName();
    lastParams = record.getParameters();
    lastThrown = record.getThrown();
    lastMessage = record.getMessage();
}