getThrowableInformation ( )源码实例Demo

org.apache.log4j.spi.LoggingEvent#getThrowableInformation ( )源码实例Demo

下面列出了org.apache.log4j.spi.LoggingEvent#getThrowableInformation ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ecs-logging-java   文件: EcsLayout.java
@Override
public String format(LoggingEvent event) {
    StringBuilder builder = new StringBuilder();
    EcsJsonSerializer.serializeObjectStart(builder, event.getTimeStamp());
    EcsJsonSerializer.serializeLogLevel(builder, event.getLevel().toString());
    EcsJsonSerializer.serializeFormattedMessage(builder, event.getRenderedMessage());
    EcsJsonSerializer.serializeServiceName(builder, serviceName);
    EcsJsonSerializer.serializeEventDataset(builder, eventDataset);
    EcsJsonSerializer.serializeThreadName(builder, event.getThreadName());
    EcsJsonSerializer.serializeLoggerName(builder, event.getLoggerName());
    EcsJsonSerializer.serializeMDC(builder, event.getProperties());
    EcsJsonSerializer.serializeTag(builder, event.getNDC());
    if (includeOrigin) {
        LocationInfo locationInformation = event.getLocationInformation();
        if (locationInformation != null) {
            EcsJsonSerializer.serializeOrigin(builder, locationInformation.getFileName(), locationInformation.getMethodName(), getLineNumber(locationInformation));
        }
    }
    ThrowableInformation throwableInformation = event.getThrowableInformation();
    if (throwableInformation != null) {
        EcsJsonSerializer.serializeException(builder, throwableInformation.getThrowable(), stackTraceAsArray);
    }
    EcsJsonSerializer.serializeObjectEnd(builder);
    return builder.toString();
}
 
源代码2 项目: sailfish-core   文件: ReportAppender.java
@Override
protected void append(LoggingEvent arg0) {

	LoggerRow row = new LoggerRow();

	row.setTimestamp(arg0.timeStamp);		// Compiler says that getTimeStamp() is deprecated
	row.setLevel(arg0.getLevel());
	row.setThread(arg0.getThreadName());
	row.setClazz(arg0.getLoggerName());
	row.setMessage(arg0.getRenderedMessage());

	if(arg0.getThrowableInformation() != null){
		row.setEx((Exception)arg0.getThrowableInformation().getThrowable());
	}

	rows.add(row);
}
 
源代码3 项目: n4js   文件: EclipseLogAppender.java
@Override
protected void append(LoggingEvent event) {
	if (isDoLog(event.getLevel())) {
		String logString = layout.format(event);

		ILog myLog = getLog();
		if (myLog != null) {
			String loggerName = event.getLoggerName();
			int severity = mapLevel(event.getLevel());
			final Throwable throwable = event.getThrowableInformation() != null ? event.getThrowableInformation()
					.getThrowable() : null;
			IStatus status = createStatus(severity, loggerName, logString, throwable);

			// Injector injector = N4JSActivator.getInstance().getInjector(N4JSActivator.ORG_ECLIPSE_N4JS_N4JS);
			// if (injector != null) {
			getLog().log(status);
			// }
		} else {
			// nothing to do (message should be logged to stdout by default appender)
		}
	}
}
 
private String getThrowableStr(LoggingEvent event) {
  ThrowableInformation throwable = event.getThrowableInformation();
  if (throwable == null) {
    return null;
  }
  StringBuilder sb = new StringBuilder();
  boolean isFirst = true;
  for (String s : throwable.getThrowableStrRep()) {
    if (isFirst) {
      isFirst = false;
    } else {
      sb.append(System.getProperty("line.separator"));
    }
    sb.append(s);
  }
  return sb.toString();
}
 
源代码5 项目: xtext-eclipse   文件: EclipseLogAppender.java
@Override
protected void append(LoggingEvent event) {
	if (isDoLog(event.getLevel())) {
		String logString = layout.format(event);

		ILog myLog = getLog();
		if (myLog != null) {
			String loggerName = event.getLoggerName();
			int severity = mapLevel(event.getLevel());
			final Throwable throwable = event.getThrowableInformation() != null ? event.getThrowableInformation()
					.getThrowable() : null;
			IStatus status = createStatus(severity, loggerName, logString, throwable);
			getLog().log(status);
		} else {
			// nothing to do (message should be logged to stdout by default appender)
		}
	}
}
 
源代码6 项目: yacy_grid_mcp   文件: LogAppender.java
@Override
public void append(LoggingEvent event) {
    if (event == null) return;
    String line = this.layout.format(event);
    if (line != null) this.lines.add(line);
    if (event.getThrowableInformation() != null) {
        for (String t: event.getThrowableStrRep()) if (t != null)  this.lines.add(t + "\n");
    }
    if (this.a.incrementAndGet() % 100 == 0) {
        clean(this.maxlines);
        this.a.set(0);
    }
}
 
源代码7 项目: unitime   文件: MessageLogAppender.java
@Override
protected void append(LoggingEvent event) {
	if (!event.getLevel().isGreaterOrEqual(getMinLevel())) return;
	if (event.getLogger().equals(MessageLogAppender.class.getName())) return;
	
	MessageLog m = new MessageLog();
	m.setLevel(event.getLevel().toInt());

	String logger = event.getLoggerName();
	if (logger.indexOf('.') >= 0) logger = logger.substring(logger.lastIndexOf('.') + 1);
	m.setLogger(logger.length() > 255 ? logger.substring(0, 255) : logger);
	
	m.setMessage(event.getMessage() == null ? null : event.getMessage().toString());
	
	m.setTimeStamp(new Date(event.getTimeStamp()));
	
	m.setNdc(event.getNDC());
	
	String thread = event.getThreadName();
	m.setThread(thread == null ? null : thread.length() > 100 ? thread.substring(0, 100) : thread);
	
	Throwable t = (event.getThrowableInformation() != null ? event.getThrowableInformation().getThrowable() : null);
	if (t != null) {
		String ex = "";
		while (t != null) {
			String clazz = t.getClass().getName();
			if (clazz.indexOf('.') >= 0) clazz = clazz.substring(1 + clazz.lastIndexOf('.'));
			if (!ex.isEmpty()) ex += "\n";
			ex += clazz + ": " + t.getMessage();
			if (t.getStackTrace() != null && t.getStackTrace().length > 0)
				ex += " (at " + t.getStackTrace()[0].getFileName() + ":" + t.getStackTrace()[0].getLineNumber() + ")";
			t = t.getCause();
		}
		if (!ex.isEmpty())
			m.setException(ex);
	}
	
	getSaver().add(m);
}
 
源代码8 项目: hadoop   文件: LogVerificationAppender.java
public int countExceptionsWithMessage(final String text) {
  int count = 0;
  for (LoggingEvent e: getLog()) {
    ThrowableInformation t = e.getThrowableInformation();
    if (t != null) {
      String m = t.getThrowable().getMessage();
      if (m.contains(text)) {
        count++;
      }
    }
  }
  return count;
}
 
源代码9 项目: spliceengine   文件: MaskPatternLayout.java
@Override
public String format(LoggingEvent event) {
    if (maskPattern == null || !(event.getMessage() instanceof String)) {
        return super.format(event);
    }

    String message = event.getRenderedMessage();
    String maskedMessage = maskMessage(message, maskPattern, maskString);
    Throwable throwable = event.getThrowableInformation() != null ?
            event.getThrowableInformation().getThrowable() : null;
    LoggingEvent maskedEvent = new LoggingEvent(event.fqnOfCategoryClass,
                Logger.getLogger(event.getLoggerName()), event.timeStamp,
                event.getLevel(), maskedMessage, throwable);
    return super.format(maskedEvent);
}
 
源代码10 项目: bender   文件: BenderLayout.java
@Override
public String format(LoggingEvent event) {
  BenderLogEntry entry = new BenderLogEntry();
  entry.threadName = event.getThreadName();
  entry.posixTimestamp = event.getTimeStamp();
  entry.timestamp = FORMATTER.print(entry.posixTimestamp);
  entry.message = event.getRenderedMessage();
  entry.level = event.getLevel().toString();
  entry.logger = event.getLogger().getName();
  entry.alias = ALIAS;
  entry.version = VERSION;

  if (event.getThrowableInformation() != null) {
    final ThrowableInformation throwableInfo = event.getThrowableInformation();
    ExceptionLog ex = new ExceptionLog();

    if (throwableInfo.getThrowable().getClass().getCanonicalName() != null) {
      ex.clazz = throwableInfo.getThrowable().getClass().getCanonicalName();
    }
    if (throwableInfo.getThrowable().getMessage() != null) {
      ex.message = throwableInfo.getThrowable().getMessage();
    }
    if (throwableInfo.getThrowableStrRep() != null) {
      Arrays.asList(throwableInfo.getThrowableStrRep()).forEach(m -> {
        ex.stacktrace.add(m.replaceAll("\\t", "   "));
      });
    }
    entry.exception = ex;
  }

  LocationInfo locinfo = event.getLocationInformation();
  entry.file = locinfo.getFileName();
  entry.lineNumber = Integer.parseInt(locinfo.getLineNumber());
  entry.method = locinfo.getMethodName();
  entry.clazz = locinfo.getClassName();

  return GSON.toJson(entry) + "\n";
}
 
源代码11 项目: big-c   文件: LogVerificationAppender.java
public int countExceptionsWithMessage(final String text) {
  int count = 0;
  for (LoggingEvent e: getLog()) {
    ThrowableInformation t = e.getThrowableInformation();
    if (t != null) {
      String m = t.getThrowable().getMessage();
      if (m.contains(text)) {
        count++;
      }
    }
  }
  return count;
}
 
源代码12 项目: big-c   文件: Log4Json.java
/**
 * Convert an event to JSON
 *
 * @param writer the destination writer
 * @param event the event -must not be null
 * @return the writer
 * @throws IOException on problems generating the JSON
 */
public Writer toJson(final Writer writer, final LoggingEvent event)
    throws IOException {
  ThrowableInformation ti = event.getThrowableInformation();
  toJson(writer,
         event.getLoggerName(),
         event.getTimeStamp(),
         event.getLevel().toString(),
         event.getThreadName(),
         event.getRenderedMessage(),
         ti);
  return writer;
}
 
源代码13 项目: spectator   文件: SpectatorAppender.java
@Override protected void append(LoggingEvent event) {
  final LevelTag level = LevelTag.get(event.getLevel());
  registry.counter(numMessages[level.ordinal()]).increment();

  ThrowableInformation info = event.getThrowableInformation();
  if (info != null) {
    LocationInfo loc = event.getLocationInformation();
    final String file = (loc == null) ? "unknown" : loc.getFileName();
    Id stackTraceId = numStackTraces[level.ordinal()]
        .withTag("exception", info.getThrowable().getClass().getSimpleName())
        .withTag("file", file);
    registry.counter(stackTraceId).increment();
  }
}
 
源代码14 项目: cacheonix-core   文件: JListView.java
public Component getListCellRendererComponent(JList list,
					Object value, 
					int index, // cell index
					boolean isSelected, 
					boolean cellHasFocus) {

     //      System.out.println(o + " ============== " + i++);
     //LogLog.error("=======", new Exception());
     //setIcon(longIcon);
     if(value instanceof LoggingEvent) {
LoggingEvent event = (LoggingEvent) value;
String str = layout.format(event);
String t = event.getThrowableInformation();

if(t != null) {
  setText(str + Layout.LINE_SEP + t);
} else {	
  setText(str);
}

     } else {
setText(value.toString());
     }


     return this;
   }
 
源代码15 项目: cacheonix-core   文件: JTableAppender.java
public Component getTableCellRendererComponent(JTable table,
					   Object value,
					   boolean isSelected,
					   boolean hasFocus,
					   int row,
					   int column) {

     System.out.println(o + " ============== " + i++);
     //LogLog.error("=======", new Exception());
     //setIcon(longIcon);
     if(value instanceof LoggingEvent) {
LoggingEvent event = (LoggingEvent) value;
String str = layout.format(event);
String t = event.getThrowableInformation();

if(t != null) {
  System.out.println("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
  setText(str + Layout.LINE_SEP + t);
} else {	
  setText(str);
}

     } else {
setText(value.toString());
     }


     return this;
   }
 
源代码16 项目: javamelody   文件: Log4JAppender.java
/**
 * {@inheritDoc}
 */
@Override
protected void append(LoggingEvent event) {
	final Throwable throwable;
	if (event.getThrowableInformation() == null) {
		throwable = null;
	} else {
		throwable = event.getThrowableInformation().getThrowable();
	}
	LoggingHandler.addErrorLogToCounter(getLayout().format(event), throwable);
}
 
源代码17 项目: otroslogviewer   文件: Log4jUtil.java
public static LogData translateLog4j(LoggingEvent event) {
  LogData ld = new LogData();
  ld.setDate(new Date(event.getTimeStamp()));
  StringBuilder sb = new StringBuilder();
  sb.append(event.getMessage());
  if (event.getThrowableInformation() != null) {
    String[] throwableStrRep = event.getThrowableInformation().getThrowableStrRep();
    for (String string : throwableStrRep) {
      sb.append('\n');
      sb.append(string);
    }
  }
  ld.setMessage(sb.toString().trim());

  ld.setLevel(parseLevel(event.getLevel().toString()));
  ld.setClazz(event.getLocationInformation().getClassName());
  ld.setMethod(event.getLocationInformation().getMethodName());
  ld.setFile(event.getLocationInformation().getFileName());
  ld.setLine(event.getLocationInformation().getLineNumber());
  ld.setNDC(event.getNDC());
  ld.setThread(event.getThreadName());
  ld.setLoggerName(event.getLoggerName());

  ld.setProperties(IMMUTABLE_EMPTY_MAP);
  Map properties = event.getProperties();
  if (properties != null) {
    Map<String, String> props = new HashMap<>(properties.size());
    for (Object key : properties.keySet()) {
      String value = Optional
        .ofNullable(properties.get(key))
        .map(Object::toString)
        .orElse("");
      if (StringUtils.isNotBlank(value)) {
        props.put(key.toString(), value);
      }
    }
    if (props.size() > 0) {
      ld.setProperties(props);
    }
  }

  return ld;
}
 
源代码18 项目: sftp-fs   文件: SFTPFileSystemLoggingTest.java
@Test
public void testLogging() throws IOException {
    URI uri = getURI();
    try (SFTPFileSystem fs = newFileSystem(uri, createEnv())) {
        SFTPFileSystemProvider.keepAlive(fs);
    }
    URI brokenUri;
    try (ServerSocket serverSocket = new ServerSocket(0)) {
        brokenUri = URI.create("sftp://localhost:" + serverSocket.getLocalPort());
    }
    assertThrows(IOException.class, () -> FileSystems.newFileSystem(brokenUri, createEnv()));

    ArgumentCaptor<LoggingEvent> captor = ArgumentCaptor.forClass(LoggingEvent.class);
    verify(appender, atLeast(1)).doAppend(captor.capture());
    List<Object> debugMessages = new ArrayList<>();
    Set<String> names = new HashSet<>();
    Set<Level> levels = new HashSet<>();
    List<Throwable> thrown = new ArrayList<>();
    for (LoggingEvent event : captor.getAllValues()) {
        names.add(event.getLoggerName());
        levels.add(event.getLevel());
        if (Level.DEBUG.equals(event.getLevel())) {
            debugMessages.add(event.getMessage());
        }
        if (event.getThrowableInformation() != null) {
            thrown.add(event.getThrowableInformation().getThrowable());
        }
    }

    assertThat(names, contains(SSHChannelPool.class.getName()));
    assertThat(levels, contains(Level.DEBUG));

    String hostname = uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        assertThat(debugMessages, hasItem("Creating SSHChannelPool to " + hostname + " with poolSize 1 and poolWaitTimeout 0"));
        assertThat(debugMessages, hasItem("Created SSHChannelPool to " + hostname + " with poolSize 1"));
    } else {
        assertThat(debugMessages, hasItem("Creating SSHChannelPool to " + hostname + ":" + port + " with poolSize 1 and poolWaitTimeout 0"));
        assertThat(debugMessages, hasItem("Created SSHChannelPool to " + hostname + ":" + port + " with poolSize 1"));
    }
    assertThat(debugMessages, hasItem("Failed to create SSHChannelPool, disconnecting all created channels"));
    assertThat(debugMessages, hasItem(new RegexMatcher("Created new channel with id 'channel-\\d+' \\(pooled: true\\)")));
    assertThat(debugMessages, hasItem(new RegexMatcher("Took channel 'channel-\\d+' from pool, current pool size: 0")));
    assertThat(debugMessages, hasItem(new RegexMatcher("Reference count for channel 'channel-\\d+' increased to 1")));
    assertThat(debugMessages, hasItem(new RegexMatcher("Reference count for channel 'channel-\\d+' decreased to 0")));
    assertThat(debugMessages, hasItem(new RegexMatcher("Returned channel 'channel-\\d+' to pool, current pool size: 1")));
    assertThat(debugMessages, hasItem("Drained pool for keep alive"));
    assertThat(debugMessages, hasItem("Drained pool for close"));
    assertThat(debugMessages, hasItem(new RegexMatcher("Disconnected channel 'channel-\\d+'")));

    assertThat(thrown, contains(Matchers.<Throwable>instanceOf(IOException.class)));
}
 
源代码19 项目: xio   文件: GlogLayout.java
@Override
public Throwable getThrowable(LoggingEvent record) {
  ThrowableInformation throwableInformation = record.getThrowableInformation();
  return throwableInformation != null ? throwableInformation.getThrowable() : null;
}
 
源代码20 项目: samza   文件: StreamAppender.java
private LoggingEvent subLog(LoggingEvent event) {
  return new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(), event.getTimeStamp(),
      event.getLevel(), subAppend(event), event.getThreadName(), event.getThrowableInformation(),
      event.getNDC(), event.getLocationInformation(), event.getProperties());
}