public static AbstractLoggingException getFromThrowableProxy(ThrowableProxy proxy) { if (proxy != null) { Throwable eventException = proxy.getThrowable(); if (eventException instanceof AbstractLoggingException) { return (AbstractLoggingException) eventException; } else if (eventException.getCause() instanceof AbstractLoggingException) { // for spring boot projects there's a generic exception wrapper // let's try to cast the cause instead return (AbstractLoggingException) eventException.getCause(); } else { triggerBadImplementationLog(eventException); return null; } } return null; }
private void appendStackTrace(StringBuilder log, ThrowableProxy proxy) { if (proxy != null) { Stream<StackTraceElementProxy> trace = Arrays.stream(proxy.getStackTraceElementProxyArray()); trace.forEach(step -> { String string = step.toString(); log.append(CoreConstants.TAB).append(string); ThrowableProxyUtil.subjoinPackagingData(log, step); log.append(CoreConstants.LINE_SEPARATOR); }); trace.close(); } }
private void loopCauses(StringBuilder log, ThrowableProxy parentProxy, int depth) { ThrowableProxy cause = (ThrowableProxy) parentProxy.getCause(); if (cause != null) { log.append(String.format( "Caused by: %s: %s", cause.getThrowable().getClass().getCanonicalName(), cause.getThrowable().getMessage() )); log.append(CoreConstants.LINE_SEPARATOR); } appendStackTrace(log, cause); if (cause != null && depth < STACKTRACE_DEPTH) { loopCauses(log, cause, depth + 1); } }
@Override public FilterReply decide(ILoggingEvent event) { if (event.getFormattedMessage().contains("Received 404 error, please notify the developer and include the URL (")) return FilterReply.DENY; if (event.getMarker() != Markers.NO_ANNOUNCE && Launcher.getInstance().getClient().isReady() && event.getLevel() == Level.ERROR) { String msg = event.getFormattedMessage(); if (event.getThrowableProxy() != null && event.getThrowableProxy() instanceof ThrowableProxy) { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") Throwable throwable = ((ThrowableProxy) event.getThrowableProxy()).getThrowable(); if (throwable != null) { msg += ' '; StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); msg += sw.toString(); pw.close(); } } Messages.send(msg, Launcher.getInstance().getClient().getChannelByID("233632081110892546")); } return FilterReply.NEUTRAL; }
@Override public FilterReply decide(ILoggingEvent event) { String msg = event.getFormattedMessage(); if (msg.startsWith("Received 40")) { return FilterReply.DENY; } if (msg.startsWith("Attempt to send message on closed")) { return FilterReply.DENY; } if (event.getMarker() != Markers.NO_ANNOUNCE && FlareBot.getInstance().getClient() != null && FlareBot.getInstance().getClient().isReady() && event.getLevel() == Level.ERROR) { EXECUTOR.submit(() -> { Throwable throwable = null; if (event.getThrowableProxy() != null && event.getThrowableProxy() instanceof ThrowableProxy) { throwable = ((ThrowableProxy) event.getThrowableProxy()).getThrowable(); } if (throwable != null) { MessageUtils.sendException(msg, throwable, FlareBot.getInstance().getUpdateChannel()); } else MessageUtils.sendMessage(msg, FlareBot.getInstance().getUpdateChannel()); }); } return FilterReply.NEUTRAL; }
@Test public void testAddException() throws Exception { //given final Exception throwable = new Exception("Some exception"); final StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); ThrowableProxy throwableProxy = new ThrowableProxy(throwable); //when LogbackUtil.addException(throwableProxy,"Message!", builder); //then final LogData logData = builder.build(); assertEquals(logData.getMessage(), "Message!\n" + stringWriter.getBuffer().toString()); }
@Test public void testEncodeArrayWithException() throws Exception { final LoggingEvent event = new LoggingEvent(); event.setLevel(Level.INFO); event.setMarker(StenoMarker.ARRAY_MARKER); event.setMessage("logEvent"); event.setLoggerContextRemoteView(_context.getLoggerContextRemoteView()); event.setTimeStamp(0); event.setThrowableProxy(new ThrowableProxy(new NullPointerException("npe!"))); final Object[] argArray = new Object[2]; argArray[0] = new String[]{}; argArray[1] = new Object[]{}; event.setArgumentArray(argArray); // CHECKSTYLE.OFF: IllegalInstantiation - This is valid case. final String logOutput = new String(_encoder.encode(event), _encoder.getCharset()); // CHECKSTYLE.ON: IllegalInstantiation assertOutput("StenoEncoderTest.testEncodeArrayWithException.json", logOutput); assertMatchesJsonSchema(logOutput); }
@Test public void testEncodeArrayWithCausedException() throws Exception { final LoggingEvent event = new LoggingEvent(); event.setLevel(Level.INFO); event.setMarker(StenoMarker.ARRAY_MARKER); event.setMessage("logEvent"); event.setLoggerContextRemoteView(_context.getLoggerContextRemoteView()); event.setTimeStamp(0); event.setThrowableProxy(new ThrowableProxy(new UnsupportedOperationException("uoe!", new NullPointerException("npe!")))); final Object[] argArray = new Object[2]; argArray[0] = new String[]{}; argArray[1] = new Object[]{}; event.setArgumentArray(argArray); // CHECKSTYLE.OFF: IllegalInstantiation - This is valid case. final String logOutput = new String(_encoder.encode(event), _encoder.getCharset()); // CHECKSTYLE.ON: IllegalInstantiation assertOutput("StenoEncoderTest.testEncodeArrayWithCausedException.json", logOutput); assertMatchesJsonSchema(logOutput); }
@Test public void testEncodeArrayWithSuppressedException() throws Exception { final LoggingEvent event = new LoggingEvent(); event.setLevel(Level.INFO); event.setMarker(StenoMarker.ARRAY_MARKER); event.setMessage("logEvent"); event.setLoggerContextRemoteView(_context.getLoggerContextRemoteView()); event.setTimeStamp(0); final Throwable throwable = new NullPointerException("npe!"); throwable.addSuppressed(new UnsupportedOperationException("uoe!")); event.setThrowableProxy(new ThrowableProxy(throwable)); final Object[] argArray = new Object[2]; argArray[0] = new String[]{}; argArray[1] = new Object[]{}; event.setArgumentArray(argArray); // CHECKSTYLE.OFF: IllegalInstantiation - This is valid case. // CHECKSTYLE.OFF: IllegalInstantiation - This is valid case. final String logOutput = new String(_encoder.encode(event), _encoder.getCharset()); // CHECKSTYLE.ON: IllegalInstantiation // CHECKSTYLE.ON: IllegalInstantiation assertOutput("StenoEncoderTest.testEncodeArrayWithSuppressedException.json", logOutput); assertMatchesJsonSchema(logOutput); }
@Test @SuppressFBWarnings(value = "SIC_INNER_SHOULD_BE_STATIC_ANON") public void testEncodeArrayWithNullSuppressedException() throws Exception { final LoggingEvent event = new LoggingEvent(); event.setLevel(Level.INFO); event.setMarker(StenoMarker.ARRAY_MARKER); event.setMessage("logEvent"); event.setLoggerContextRemoteView(_context.getLoggerContextRemoteView()); event.setTimeStamp(0); event.setThrowableProxy(new ThrowableProxy(new NullPointerException("npe!")) { @Override @SuppressFBWarnings(value = "PZLA_PREFER_ZERO_LENGTH_ARRAYS") public IThrowableProxy[] getSuppressed() { return null; } }); final Object[] argArray = new Object[2]; argArray[0] = new String[]{}; argArray[1] = new Object[]{}; event.setArgumentArray(argArray); // CHECKSTYLE.OFF: IllegalInstantiation - This is valid case. final String logOutput = new String(_encoder.encode(event), _encoder.getCharset()); // CHECKSTYLE.ON: IllegalInstantiation assertOutput("StenoEncoderTest.testEncodeArrayWithNullSuppressedException.json", logOutput); assertMatchesJsonSchema(logOutput); }
@Override protected void append(ILoggingEvent event) { final IThrowableProxy throwableProxy = event.getThrowableProxy(); final Map<String, String> mdc = event.getMDCPropertyMap(); if ((throwableProxy != null) && (throwableProxy instanceof ThrowableProxy)) { ThrowableProxy proxy = (ThrowableProxy) throwableProxy; if (proxy.getThrowable() != null) { Map<String, String> params = new HashMap<>(mdc); if (!mdc.containsKey(MESSAGE_PARAM)) { params.put(MESSAGE_PARAM, event.getFormattedMessage()); } noticeError(proxy.getThrowable(), params); return; } } noticeError(event.getFormattedMessage(), mdc); }
@Override public FilterReply decide(ILoggingEvent event) { final IThrowableProxy throwableProxy = event.getThrowableProxy(); if (throwableProxy == null) { return FilterReply.NEUTRAL; } if (!(throwableProxy instanceof ThrowableProxy)) { return FilterReply.NEUTRAL; } final ThrowableProxy throwableProxyImpl = (ThrowableProxy) throwableProxy; final Throwable throwable = throwableProxyImpl.getThrowable(); if (java.nio.channels.ClosedChannelException.class.isInstance(throwable)) { return FilterReply.DENY; } return FilterReply.NEUTRAL; }
private LoggingEvent makeEvent(Level level, String message, Throwable th) { LoggingEvent event = new LoggingEvent(); event.setLoggerName(CloudWatchAppender.class.getName()); event.setLevel(level); event.setMessage(message); event.setTimeStamp(System.currentTimeMillis()); if (th != null) { event.setThrowableProxy(new ThrowableProxy(th)); } return event; }
@Override public boolean matches(Object item) { if (item instanceof ThrowableProxy) { return expectedException.matches(((ThrowableProxy) item).getThrowable()); } return false; }
@Test public void match_when_ThrowableProxy_contains_exception() { ExpectedExceptionMatcher expectedExceptionMatcher = new ExpectedExceptionMatcher(isA(RuntimeException.class)); boolean matches = expectedExceptionMatcher.matches(new ThrowableProxy(new RuntimeException())); assertThat(matches).isTrue(); }
@Test public void not_match_when_ThrowableProxy_contains_another_exception() { ExpectedExceptionMatcher expectedExceptionMatcher = new ExpectedExceptionMatcher(isA(IllegalArgumentException.class)); boolean matches = expectedExceptionMatcher.matches(new ThrowableProxy(new IllegalStateException())); assertThat(matches).isFalse(); }
@Override public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException { if (require) { ThrowableProxy proxy = (ThrowableProxy) event.getThrowableProxy(); AbstractLoggingException exception = AbstractLoggingException.getFromThrowableProxy(proxy); if (exception != null) { JsonWritingUtils.writeStringField(generator, getFieldName(), getValue(exception)); } } }
@Override public String doLayout(ILoggingEvent event) { Instant instant = Instant.ofEpochMilli(event.getTimeStamp()); ZonedDateTime dateTime = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()); StringBuilder log = new StringBuilder(dateTime.format(dateFormat)); log.append(String.format(" %-5s", event.getLevel().levelStr)); if (requireThread) { log.append(String.format(" [%s]", event.getThreadName())); } int lineNumber = event.getCallerData().length > 0 ? event.getCallerData()[0].getLineNumber() : 0; log.append(String.format(" %s:%d: ", event.getLoggerName(), lineNumber)); ThrowableProxy proxy = (ThrowableProxy) event.getThrowableProxy(); if (requireAlertLevel || requireErrorCode) { appendExtraExceptionFlags(log, AbstractLoggingException.getFromThrowableProxy(proxy)); } log.append(event.getFormattedMessage()).append(CoreConstants.LINE_SEPARATOR); appendStackTrace(log, proxy); if (proxy != null) { loopCauses(log, proxy, 0); } return log.toString(); }
@Override public void onLog(LogEntry logEntry) { final LoggingEvent loggingEvent = new LoggingEvent(); loggingEvent.setTimeStamp(logEntry.getTimestamp()); loggingEvent.setLoggerName(logEntry.getLoggerName()); loggingEvent.setLevel(Level.valueOf(logEntry.getLogLevel().name())); loggingEvent.setThreadName(logEntry.getThreadName()); Object [] formatObjects = new Object[] {logEntry.getHost(), getSimpleClassName(logEntry.getSourceClassName()), logEntry.getSourceMethodName(), logEntry.getFileName(), logEntry.getLineNumber(),logEntry.getMessage()}; loggingEvent.setMessage(MESSAGE_FORMAT.get().format(formatObjects)); // Prints the throwable and stack trace. LogThrowable logThrowable = logEntry.getThrowable(); if (logThrowable != null) { loggingEvent.setThrowableProxy(new ThrowableProxy(setThrowable(logThrowable))); } if (logger instanceof Logger) { ((Logger) logger).callAppenders(loggingEvent); } else { logger.info("Logger is not instance of ch.qos.logback.classic.Logger. Logger event is: {}", loggingEvent); } }
@Test public void withStackTrace() throws Exception { event.setThrowableProxy(new ThrowableProxy(new RuntimeException())); String s = converter.convert(event); System.out.println(s); assertThat(s, startsWith("java.lang.RuntimeException: null\\n at com.")); }
@Override public FilterReply decide(ILoggingEvent event) { if (!LauncherEntry.nogui &&event.getThrowableProxy() != null && event.getThrowableProxy() instanceof ThrowableProxy) { @SuppressWarnings("ThrowableResultOfMethodCallIgnored") Throwable throwable = ((ThrowableProxy) event.getThrowableProxy()).getThrowable(); if (throwable != null) { new ExceptionBox(throwable, "Cought an error in runtime!").show(); } } return FilterReply.NEUTRAL; }
private static String renderEvent(ILoggingEvent event) { Throwable throwable = null; if (event.getThrowableProxy() != null && event.getThrowableProxy() instanceof ThrowableProxy) { throwable = ((ThrowableProxy) event.getThrowableProxy()).getThrowable(); } if (throwable != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); String trace = sw.toString(); pw.close(); return formatted(event) + trace; } else return formatted(event); }
@Override public String convert(ILoggingEvent event) { StringBuilder appendTo = new StringBuilder(); IThrowableProxy tProxy = event.getThrowableProxy(); if (tProxy != null && ThrowableProxy.class.isAssignableFrom(tProxy.getClass())) { StacktraceConverter.CONVERTER.convert(((ThrowableProxy) tProxy).getThrowable(), appendTo); return appendTo.toString(); } return null; }
@Override protected void append(ILoggingEvent event) { Map<String, Object> messages = new HashMap<String, Object>(); messages.put("host", getHostname()); messages.put("app", label); messages.put("main", System.getProperty("sun.java.command")); messages.put("thread", event.getThreadName()); messages.put("level", event.getLevel().toString()); messages.put("class", event.getLoggerName()); if (event.getThrowableProxy() == null) { // Without exception messages.put("exception", "--- This.log.is.not.an.exception ---"); Throwable tempThrowable = new Throwable(); tempThrowable.setStackTrace(event.getCallerData()); messages.put("message", event.getFormattedMessage().toString()); if (event.getCallerData() != null) { messages.put("stacktrace", extractCallerData(tempThrowable)); } } else { // With exception ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy(); messages.put("exception", throwableProxy.getClassName()); messages.put("message", throwableProxy.getMessage()); messages.put("stacktrace", extractCallerData(throwableProxy.getThrowable())); } Long timeStamp = event.getTimeStamp() / 1000; service.submit(() -> { fluentLogger.log(label, messages, timeStamp); }); }
private LogStatement makeRandomLogStatement(String[] loggerNamePool) { MessageArgumentTuple mat = makeRandomMessageArgumentTuple(); String loggerName = getRandomLoggerNameFromPool(loggerNamePool); Level randomLevel = getRandomLevel(); Throwable t = getRandomThrowable(randomLevel); ThrowableProxyVO throwableProxy = null; if (t != null) { throwableProxy = ThrowableProxyVO.build(new ThrowableProxy(t)); pupulateWithPackagingData(throwableProxy.getStackTraceElementProxyArray()); } return new LogStatement(loggerName, randomLevel, mat, throwableProxy); }
@SuppressWarnings("unchecked") @Test public void layoutWithException() throws Exception { layout.setPattern("%level %thread %msg %ex"); LoggingEvent le = createLoggingEvent(); le.setThrowableProxy(new ThrowableProxy(new Exception("test Exception"))); String result = layout.doLayout(le); String stringToParse = layout.getFileHeader(); stringToParse = stringToParse + layout.getPresentationHeader(); stringToParse += result; stringToParse += "</table></body></html>"; // System.out.println(stringToParse); Document doc = parseOutput(stringToParse); Element rootElement = doc.getRootElement(); Element bodyElement = rootElement.element("body"); Element tableElement = bodyElement.element("table"); List<Element> trElementList = tableElement.elements(); Element exceptionRowElement = trElementList.get(2); Element exceptionElement = exceptionRowElement.element("td"); assertEquals(3, tableElement.elements().size()); assertTrue(exceptionElement.getText().contains( "java.lang.Exception: test Exception")); }
@Test public void withStackTrace() throws Exception { this.event.setThrowableProxy(new ThrowableProxy(new RuntimeException())); String s = this.converter.convert(this.event); assertThat(s, startsWith(LINE_SEPARATOR)); assertThat(s, endsWith(LINE_SEPARATOR)); }
private static final Throwable extractThrowable(final ILoggingEvent event) { if (event == null) { return null; } final IThrowableProxy throwableProxy = event.getThrowableProxy(); if (throwableProxy instanceof ThrowableProxy) { return ((ThrowableProxy)throwableProxy).getThrowable(); } return null; }
@Override protected void append(ILoggingEvent event) { try { ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy(); Throwable throwable = throwableProxy == null ? null : throwableProxy.getThrowable(); String message = event.getFormattedMessage(); LogLevel level = LogLevelConverter.toGradleLogLevel(event.getLevel(), event.getMarker()); outputEventListener.onOutput(new LogEvent(event.getTimeStamp(), event.getLoggerName(), level, message, throwable)); } catch (Throwable t) { // fall back to standard out t.printStackTrace(defaultStandardOut); } }
public String throwableProxyToString(IThrowableProxy throwableProxy) { String[] rootCauseStackTraceArr = ExceptionUtils.getRootCauseStackTrace(((ThrowableProxy) throwableProxy).getThrowable()); rootCauseStackTraceArr[0] = CoreConstants.CAUSED_BY + rootCauseStackTraceArr[0]; rootCauseStackTraceArr[rootCauseStackTraceArr.length - 1] += CoreConstants.LINE_SEPARATOR; return StringUtils.join(rootCauseStackTraceArr, CoreConstants.LINE_SEPARATOR); }
/** * @see com.stackify.api.common.log.EventAdapter#getThrowable(java.lang.Object) */ @Override public Throwable getThrowable(final ILoggingEvent event) { IThrowableProxy iThrowableProxy = event.getThrowableProxy(); if (iThrowableProxy != null) { if (iThrowableProxy instanceof ThrowableProxy) { ThrowableProxy throwableProxy = (ThrowableProxy) iThrowableProxy; return throwableProxy.getThrowable(); } } return null; }
/** * testGetThrowableWithoutException */ @Test public void testGetThrowableWithoutException() { ThrowableProxy proxy = Mockito.mock(ThrowableProxy.class); Mockito.when(proxy.getThrowable()).thenReturn(new NullPointerException()); ILoggingEvent event = Mockito.mock(ILoggingEvent.class); Mockito.when(event.getThrowableProxy()).thenReturn(proxy); ILoggingEventAdapter adapter = new ILoggingEventAdapter(Mockito.mock(EnvironmentDetail.class)); Throwable throwable = adapter.getThrowable(event); Assert.assertNotNull(throwable); }
protected void writeThrowable(Map<String, Object> json, ILoggingEvent event) { IThrowableProxy ti = event.getThrowableProxy(); if (ti != null) { json.put("className", ti.getClassName()); json.put("stackTrace", getStackTrace(((ThrowableProxy)ti).getThrowable())); } }
@Override public Throwable getThrowable() { Throwable result = null; IThrowableProxy throwableProxy = loggingEvent.getThrowableProxy(); if (null != throwableProxy) { if (throwableProxy instanceof ThrowableProxy) { result = ((ThrowableProxy) throwableProxy).getThrowable(); } } return result; }
@Test public void withStackTrace() throws Exception { event.setThrowableProxy(new ThrowableProxy(new RuntimeException())); String s = converter.convert(event); assertThat(s, startsWith("java.lang.RuntimeException: null\\n at com.")); }
@Test public void withStackTrace() throws Exception { this.event.setThrowableProxy(new ThrowableProxy(new RuntimeException())); String s = this.converter.convert(this.event); assertThat(s).startsWith(LINE_SEPARATOR).endsWith(LINE_SEPARATOR); }