Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

LoggentriesAppender: memory efficient concatenation for layout.ignoresThrowable() #53

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 30 additions & 11 deletions src/main/java/com/logentries/log4j/LogentriesAppender.java
Original file line number Diff line number Diff line change
Expand Up @@ -152,22 +152,41 @@ protected void append( LoggingEvent event) {
// Append stack trace if present and layout does not handle it
if (layout.ignoresThrowable()) {
String[] stack = event.getThrowableStrRep();
if (stack != null)
{
int len = stack.length;
formattedEvent += ", ";
for(int i = 0; i < len; i++)
{
formattedEvent += stack[i];
if(i < len - 1)
formattedEvent += "\u2028";
}
}
if (stack != null && stack.length > 0)
formattedEvent = appendFormatedEvent(formattedEvent, stack);
}

// Prepare to be queued
this.le_async.addLineToQueue(formattedEvent);
}
private static final String EXCEPTION_SEPARATOR = ", ";

static String appendFormatedEvent(final String formattedEvent, final String[] stack) {
final int len = stack.length;

// calculate buffer size
int buffSize = formattedEvent.length()
+ EXCEPTION_SEPARATOR.length()
+ len - 1
;
for (int i = 0; i < len; i++) {
buffSize += stack[i].length();
}

Copy link

@danilosterrapid7 danilosterrapid7 Jul 7, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are some things that might saved more cpu cycles here.
Replacing:

int buffSize = formattedEvent.length();
buffSize += EXCEPTION_SEPARATOR.length();

By:

int buffSize = formattedEvent.length() + EXCEPTION_SEPARATOR.length();

And removing from the loop:

if (i < len - 1) {
    buffSize += 1;
}

And adding after for loop:

buffSize += len - 1;

It would save... ;)

// concatenate
final StringBuilder sb = new StringBuilder(buffSize);
sb.append(formattedEvent);
sb.append(EXCEPTION_SEPARATOR);

for (int i = 0; i < len; i++) {
sb.append(stack[i]);
if (i < len - 1) {
sb.append('\u2028');
}
}
// assert sb.capacity() == sb.length();
return sb.toString();
}

/**
* Closes all connections to Logentries
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.logentries.log4j;

import static com.logentries.log4j.LogentriesAppender.*;
import static org.junit.Assert.*;

import org.junit.Test;
Expand All @@ -26,4 +27,8 @@ public void settersTest() {
assertEquals(le.le_async.getSsl(),true);
}

@Test
public void testAppendFormatedEvent() {
assertEquals("foo, a\u2028b\u2028c", appendFormatedEvent("foo", new String[]{"a","b", "c"}));
}
}