Search in sources :

Example 1 with ThrowableProxy

use of org.apache.logging.log4j.core.impl.ThrowableProxy in project graylog2-server by Graylog2.

the class LoggersResource method messages.

@GET
@Timed
@ApiOperation(value = "Get recent internal log messages")
@ApiResponses(value = { @ApiResponse(code = 404, message = "Memory appender is disabled."), @ApiResponse(code = 500, message = "Memory appender is broken.") })
@Path("/messages/recent")
@Produces(MediaType.APPLICATION_JSON)
public LogMessagesSummary messages(@ApiParam(name = "limit", value = "How many log messages should be returned", defaultValue = "500", allowableValues = "range[0, infinity]") @QueryParam("limit") @DefaultValue("500") @Min(0L) int limit, @ApiParam(name = "level", value = "Which log level (or higher) should the messages have", defaultValue = "ALL", allowableValues = "[OFF, FATAL, ERROR, WARN, INFO, DEBUG, TRACE, ALL]") @QueryParam("level") @DefaultValue("ALL") @NotEmpty String level) {
    final Appender appender = getAppender(MEMORY_APPENDER_NAME);
    if (appender == null) {
        throw new NotFoundException("Memory appender is disabled. Please refer to the example log4j.xml file.");
    }
    if (!(appender instanceof MemoryAppender)) {
        throw new InternalServerErrorException("Memory appender is not an instance of MemoryAppender. Please refer to the example log4j.xml file.");
    }
    final Level logLevel = Level.toLevel(level, Level.ALL);
    final MemoryAppender memoryAppender = (MemoryAppender) appender;
    final List<InternalLogMessage> messages = new ArrayList<>(limit);
    for (LogEvent event : memoryAppender.getLogMessages(limit)) {
        final Level eventLevel = event.getLevel();
        if (!eventLevel.isMoreSpecificThan(logLevel)) {
            continue;
        }
        final ThrowableProxy thrownProxy = event.getThrownProxy();
        final String throwable;
        if (thrownProxy == null) {
            throwable = null;
        } else {
            throwable = thrownProxy.getExtendedStackTraceAsString();
        }
        final Marker marker = event.getMarker();
        messages.add(InternalLogMessage.create(event.getMessage().getFormattedMessage(), event.getLoggerName(), eventLevel.toString(), marker == null ? null : marker.toString(), new DateTime(event.getTimeMillis(), DateTimeZone.UTC), throwable, event.getThreadName(), event.getContextData().toMap()));
    }
    return LogMessagesSummary.create(messages);
}
Also used : Appender(org.apache.logging.log4j.core.Appender) MemoryAppender(org.graylog2.log4j.MemoryAppender) MemoryAppender(org.graylog2.log4j.MemoryAppender) LogEvent(org.apache.logging.log4j.core.LogEvent) ArrayList(java.util.ArrayList) NotFoundException(javax.ws.rs.NotFoundException) Marker(org.apache.logging.log4j.Marker) ThrowableProxy(org.apache.logging.log4j.core.impl.ThrowableProxy) DateTime(org.joda.time.DateTime) InternalLogMessage(org.graylog2.rest.models.system.loggers.responses.InternalLogMessage) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Level(org.apache.logging.log4j.Level) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 2 with ThrowableProxy

use of org.apache.logging.log4j.core.impl.ThrowableProxy in project logging-log4j2 by apache.

the class ExtendedThrowablePatternConverterTest method testDeserializedLogEventWithThrowableProxyButNoThrowable.

@Test
public void testDeserializedLogEventWithThrowableProxyButNoThrowable() {
    final ExtendedThrowablePatternConverter converter = ExtendedThrowablePatternConverter.newInstance(null, null);
    final Throwable originalThrowable = new Exception("something bad happened");
    final ThrowableProxy throwableProxy = new ThrowableProxy(originalThrowable);
    final Throwable deserializedThrowable = null;
    final Log4jLogEvent event = //
    Log4jLogEvent.newBuilder().setLoggerName(//
    "testLogger").setLoggerFqcn(//
    this.getClass().getName()).setLevel(//
    Level.DEBUG).setMessage(//
    new SimpleMessage("")).setThrown(//
    deserializedThrowable).setThrownProxy(//
    throwableProxy).setTimeMillis(0).build();
    final StringBuilder sb = new StringBuilder();
    converter.format(event, sb);
    final String result = sb.toString();
    assertTrue(result, result.contains(originalThrowable.getMessage()));
    assertTrue(result, result.contains(originalThrowable.getStackTrace()[0].getMethodName()));
}
Also used : Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) ThrowableProxy(org.apache.logging.log4j.core.impl.ThrowableProxy) Test(org.junit.Test)

Example 3 with ThrowableProxy

use of org.apache.logging.log4j.core.impl.ThrowableProxy in project logging-log4j2 by apache.

the class ExtendedThrowablePatternConverter method format.

/**
     * {@inheritDoc}
     */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final ThrowableProxy proxy = event.getThrownProxy();
    final Throwable throwable = event.getThrown();
    if ((throwable != null || proxy != null) && options.anyLines()) {
        if (proxy == null) {
            super.format(event, toAppendTo);
            return;
        }
        String suffix = getSuffix(event);
        final String extStackTrace = proxy.getExtendedStackTraceAsString(options.getIgnorePackages(), options.getTextRenderer(), suffix);
        final int len = toAppendTo.length();
        if (len > 0 && !Character.isWhitespace(toAppendTo.charAt(len - 1))) {
            toAppendTo.append(' ');
        }
        if (!options.allLines() || !Strings.LINE_SEPARATOR.equals(options.getSeparator())) {
            final StringBuilder sb = new StringBuilder();
            final String[] array = extStackTrace.split(Strings.LINE_SEPARATOR);
            final int limit = options.minLines(array.length) - 1;
            for (int i = 0; i <= limit; ++i) {
                sb.append(array[i]);
                if (i < limit) {
                    sb.append(options.getSeparator());
                }
            }
            toAppendTo.append(sb.toString());
        } else {
            toAppendTo.append(extStackTrace);
        }
    }
}
Also used : ThrowableProxy(org.apache.logging.log4j.core.impl.ThrowableProxy)

Example 4 with ThrowableProxy

use of org.apache.logging.log4j.core.impl.ThrowableProxy in project logging-log4j2 by apache.

the class RootThrowablePatternConverter method format.

/**
     * {@inheritDoc}
     */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final ThrowableProxy proxy = event.getThrownProxy();
    final Throwable throwable = event.getThrown();
    if (throwable != null && options.anyLines()) {
        if (proxy == null) {
            super.format(event, toAppendTo);
            return;
        }
        String suffix = getSuffix(event);
        final String trace = proxy.getCauseStackTraceAsString(options.getIgnorePackages(), suffix);
        final int len = toAppendTo.length();
        if (len > 0 && !Character.isWhitespace(toAppendTo.charAt(len - 1))) {
            toAppendTo.append(' ');
        }
        if (!options.allLines() || !Strings.LINE_SEPARATOR.equals(options.getSeparator())) {
            final StringBuilder sb = new StringBuilder();
            final String[] array = trace.split(Strings.LINE_SEPARATOR);
            final int limit = options.minLines(array.length) - 1;
            for (int i = 0; i <= limit; ++i) {
                sb.append(array[i]);
                if (i < limit) {
                    sb.append(options.getSeparator());
                }
            }
            toAppendTo.append(sb.toString());
        } else {
            toAppendTo.append(trace);
        }
    }
}
Also used : ThrowableProxy(org.apache.logging.log4j.core.impl.ThrowableProxy)

Example 5 with ThrowableProxy

use of org.apache.logging.log4j.core.impl.ThrowableProxy in project logging-log4j2 by apache.

the class RingBufferLogEventTest method testSerializationDeserialization.

@Test
public void testSerializationDeserialization() throws IOException, ClassNotFoundException {
    final RingBufferLogEvent evt = new RingBufferLogEvent();
    final String loggerName = "logger.name";
    final Marker marker = null;
    final String fqcn = "f.q.c.n";
    final Level level = Level.TRACE;
    final Message data = new SimpleMessage("message");
    final Throwable t = new InternalError("not a real error");
    final ContextStack contextStack = null;
    final String threadName = "main";
    final StackTraceElement location = null;
    final long currentTimeMillis = 12345;
    final long nanoTime = 1;
    evt.setValues(null, loggerName, marker, fqcn, level, data, t, (StringMap) evt.getContextData(), contextStack, -1, threadName, -1, location, currentTimeMillis, nanoTime);
    ((StringMap) evt.getContextData()).putValue("key", "value");
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final ObjectOutputStream out = new ObjectOutputStream(baos);
    out.writeObject(evt);
    final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
    final RingBufferLogEvent other = (RingBufferLogEvent) in.readObject();
    assertEquals(loggerName, other.getLoggerName());
    assertEquals(marker, other.getMarker());
    assertEquals(fqcn, other.getLoggerFqcn());
    assertEquals(level, other.getLevel());
    assertEquals(data, other.getMessage());
    assertNull("null after serialization", other.getThrown());
    assertEquals(new ThrowableProxy(t), other.getThrownProxy());
    assertEquals(evt.getContextData(), other.getContextData());
    assertEquals(contextStack, other.getContextStack());
    assertEquals(threadName, other.getThreadName());
    assertEquals(location, other.getSource());
    assertEquals(currentTimeMillis, other.getTimeMillis());
}
Also used : StringMap(org.apache.logging.log4j.util.StringMap) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Message(org.apache.logging.log4j.message.Message) SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Marker(org.apache.logging.log4j.Marker) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MutableThreadContextStack(org.apache.logging.log4j.spi.MutableThreadContextStack) ContextStack(org.apache.logging.log4j.ThreadContext.ContextStack) ObjectOutputStream(java.io.ObjectOutputStream) ThrowableProxy(org.apache.logging.log4j.core.impl.ThrowableProxy) ByteArrayInputStream(java.io.ByteArrayInputStream) Level(org.apache.logging.log4j.Level) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Aggregations

ThrowableProxy (org.apache.logging.log4j.core.impl.ThrowableProxy)6 Marker (org.apache.logging.log4j.Marker)3 SimpleMessage (org.apache.logging.log4j.message.SimpleMessage)3 Level (org.apache.logging.log4j.Level)2 Log4jLogEvent (org.apache.logging.log4j.core.impl.Log4jLogEvent)2 Test (org.junit.Test)2 Timed (com.codahale.metrics.annotation.Timed)1 ApiOperation (io.swagger.annotations.ApiOperation)1 ApiResponses (io.swagger.annotations.ApiResponses)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 ObjectInputStream (java.io.ObjectInputStream)1 ObjectOutputStream (java.io.ObjectOutputStream)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 GET (javax.ws.rs.GET)1 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)1 NotFoundException (javax.ws.rs.NotFoundException)1 Path (javax.ws.rs.Path)1