Skip to content

Commit

Permalink
Merge pull request #34 from hackmann/master
Browse files Browse the repository at this point in the history
Make including caller file name and line number optional
  • Loading branch information
t0xa committed Sep 17, 2012
2 parents 17ef495 + f0a8e54 commit 1aa1ef2
Show file tree
Hide file tree
Showing 10 changed files with 68 additions and 78 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ GelfAppender supports the following options:
- **originHost**: Name of the originating host; defaults to the local hostname (*optional*)
- **extractStacktrace** (true/false): Add stacktraces to the GELF message; default false (*optional*)
- **addExtendedInformation** (true/false): Add extended information like Log4j's NDC/MDC; default false (*optional*)
- **includeLocation** (true/false): Include caller file name and line number. Log4j documentation warns that generating caller location information is extremely slow and should be avoided unless execution speed is not an issue; default true (*optional*)
- **facility**: Facility which to use in the GELF message; default "gelf-java"

Logging Handler
Expand Down
9 changes: 2 additions & 7 deletions src/main/java/org/graylog2/GelfMessage.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,8 @@ public class GelfMessage {
public GelfMessage() {
}

// todo: merge these constructors.

public GelfMessage(String shortMessage, String fullMessage, Date timestamp, String level) {
this.shortMessage = shortMessage;
this.fullMessage = fullMessage;
this.javaTimestamp = timestamp.getTime();
this.level = level;
public GelfMessage(String shortMessage, String fullMessage, long timestamp, String level) {
this(shortMessage, fullMessage, timestamp, level, null, null);
}

public GelfMessage(String shortMessage, String fullMessage, Long timestamp, String level, String line, String file) {
Expand Down
10 changes: 7 additions & 3 deletions src/main/java/org/graylog2/GelfMessageFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,13 @@ public static final GelfMessage makeMessage(LoggingEvent event, GelfMessageProvi
long timeStamp = Log4jVersionChecker.getTimeStamp(event);
Level level = event.getLevel();

LocationInfo locationInformation = event.getLocationInformation();
String file = locationInformation.getFileName();
String lineNumber = locationInformation.getLineNumber();
String file = null;
String lineNumber = null;
if (provider.isIncludeLocation()) {
LocationInfo locationInformation = event.getLocationInformation();
file = locationInformation.getFileName();
lineNumber = locationInformation.getLineNumber();
}

String renderedMessage = event.getRenderedMessage();
String shortMessage;
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/org/graylog2/GelfMessageProvider.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package org.graylog2;

import org.apache.log4j.spi.LoggingEvent;

import java.util.Map;

public interface GelfMessageProvider {
Expand All @@ -10,4 +8,5 @@ public interface GelfMessageProvider {
public String getFacility();
public Map<String, String> getFields();
public boolean isAddExtendedInformation();
public boolean isIncludeLocation();
}
26 changes: 6 additions & 20 deletions src/main/java/org/graylog2/GelfSender.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package org.graylog2;

import java.io.IOException;
import java.net.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.List;

public class GelfSender {

private static final int DEFAULT_PORT = 12201;

private static final int PORT_MIN = 8000;
private static final int PORT_MAX = 8888;

private InetAddress host;
private int port;
private DatagramSocket socket;
Expand All @@ -26,22 +27,7 @@ public GelfSender(String host, int port) throws UnknownHostException, SocketExce
}

private DatagramSocket initiateSocket() throws SocketException {
int port = PORT_MIN;

DatagramSocket resultingSocket = null;
boolean binded = false;
while (!binded) {
try {
resultingSocket = new DatagramSocket(port);
binded = true;
} catch (SocketException e) {
port++;

if (port > PORT_MAX)
throw e;
}
}
return resultingSocket;
return new DatagramSocket(0);
}

public boolean sendMessage(GelfMessage message) {
Expand Down
31 changes: 17 additions & 14 deletions src/main/java/org/graylog2/log/GelfAppender.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
package org.graylog2.log;

import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.MDC;
import org.apache.log4j.spi.ErrorCode;
import org.apache.log4j.spi.LocationInfo;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ThrowableInformation;
import org.graylog2.GelfMessage;
import org.graylog2.GelfMessageFactory;
import org.graylog2.GelfMessageProvider;
import org.graylog2.GelfSender;
import org.json.simple.JSONValue;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
*
* @author Anton Yakimov
Expand All @@ -36,6 +30,7 @@ public class GelfAppender extends AppenderSkeleton implements GelfMessageProvide
private GelfSender gelfSender;
private boolean extractStacktrace;
private boolean addExtendedInformation;
private boolean includeLocation = true;
private Map<String, String> fields;

public GelfAppender() {
Expand Down Expand Up @@ -107,7 +102,15 @@ public boolean isAddExtendedInformation() {
public void setAddExtendedInformation(boolean addExtendedInformation) {
this.addExtendedInformation = addExtendedInformation;
}


public boolean isIncludeLocation() {
return this.includeLocation;
}

public void setIncludeLocation(boolean includeLocation) {
this.includeLocation = includeLocation;
}

public Map<String, String> getFields() {
if (fields == null) {
fields = new HashMap<String, String>();
Expand Down
27 changes: 18 additions & 9 deletions src/main/java/org/graylog2/log/GelfConsoleAppender.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,15 @@
*
*/
public class GelfConsoleAppender extends ConsoleAppender implements GelfMessageProvider{

private static String originHost;
private boolean extractStacktrace;
private boolean addExtendedInformation;
private boolean includeLocation = true;
private Map<String, String> fields;

// parent overrides.

public GelfConsoleAppender() {
super(); //To change body of overridden methods use File | Settings | File Templates.
}
Expand All @@ -43,29 +44,37 @@ public GelfConsoleAppender(Layout layout) {
public GelfConsoleAppender(Layout layout, String target) {
super(layout, target); //To change body of overridden methods use File | Settings | File Templates.
}

// GelfMessageProvider interface.

public void setAdditionalFields(String additionalFields) {
fields = (Map<String, String>) JSONValue.parse(additionalFields.replaceAll("'", "\""));
}

public boolean isExtractStacktrace() {
return extractStacktrace;
}

public void setExtractStacktrace(boolean extractStacktrace) {
this.extractStacktrace = extractStacktrace;
}

public boolean isAddExtendedInformation() {
return addExtendedInformation;
}

public void setAddExtendedInformation(boolean addExtendedInformation) {
this.addExtendedInformation = addExtendedInformation;
}


public boolean isIncludeLocation() {
return this.includeLocation;
}

public void setIncludeLocation(boolean includeLocation) {
this.includeLocation = includeLocation;
}

public String getOriginHost() {
return originHost;
}
Expand All @@ -86,7 +95,7 @@ public Map<String, String> getFields() {
}

// the important parts.

@Override
protected void subAppend(LoggingEvent event) {
GelfMessage gelf = GelfMessageFactory.makeMessage(event, this);
Expand Down
31 changes: 12 additions & 19 deletions src/main/java/org/graylog2/log/Log4jVersionChecker.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,22 @@
*/
public class Log4jVersionChecker {

private static boolean hasGetTimeStamp = true;
private static Method methodGetTimeStamp = null;

public static long getTimeStamp(LoggingEvent event) {

long timeStamp = System.currentTimeMillis();

if(hasGetTimeStamp && methodGetTimeStamp == null) {

hasGetTimeStamp = false;

Method[] declaredMethods = event.getClass().getDeclaredMethods();
for(Method m : declaredMethods) {
if (m.getName().equals("getTimeStamp")) {
methodGetTimeStamp = m;
hasGetTimeStamp = true;

break;
}
static {
Method[] declaredMethods = LoggingEvent.class.getDeclaredMethods();
for(Method m : declaredMethods) {
if (m.getName().equals("getTimeStamp")) {
methodGetTimeStamp = m;
break;
}
}
}

public static long getTimeStamp(LoggingEvent event) {

if(hasGetTimeStamp) {
long timeStamp = 0;
if(methodGetTimeStamp != null) {

try {
timeStamp = (Long) methodGetTimeStamp.invoke(event);
Expand All @@ -45,6 +38,6 @@ public static long getTimeStamp(LoggingEvent event) {
}
}

return timeStamp;
return timeStamp == 0 ? System.currentTimeMillis() : timeStamp;
}
}
2 changes: 1 addition & 1 deletion src/main/java/org/graylog2/logging/GelfHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ private GelfMessage makeMessage( final LogRecord record )
final GelfMessage gelfMessage =
new GelfMessage( shortMessage,
message,
new Date( record.getMillis() ),
record.getMillis(),
String.valueOf( levelToSyslogLevel( record.getLevel() ) ) );
gelfMessage.addField( "SourceClassName", record.getSourceClassName() );
gelfMessage.addField( "SourceMethodName", record.getSourceMethodName() );
Expand Down
6 changes: 3 additions & 3 deletions src/test/java/org/graylog2/GelfMessageTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class GelfMessageTest {

@Test
public void testAdditionalFieldsIds() throws Exception {
GelfMessage message = new GelfMessage("Short", "Long", new Date(), "1");
GelfMessage message = new GelfMessage("Short", "Long", System.currentTimeMillis(), "1");
message.addField("id", "LOLCAT").addField("_id", "typos in my closet");

String data = message.toJson();
Expand All @@ -29,7 +29,7 @@ public void testSendLongMessage() throws Exception {
for (int i = 0; i < 15; i++) {
longString += longString;
}
GelfMessage message = new GelfMessage("Long", longString, new Date(), "1");
GelfMessage message = new GelfMessage("Long", longString, System.currentTimeMillis(), "1");
List<byte[]> bytes2 = message.toDatagrams();
assertEquals(2, bytes2.size());
assertTrue(Arrays.equals(Arrays.copyOfRange(bytes2.get(0), 10, 11), new byte[] {0x00}));
Expand All @@ -40,7 +40,7 @@ public void testSendLongMessage() throws Exception {

@Test
public void testSimpleMessage() throws Exception {
GelfMessage message = new GelfMessage("Short", "Long", new Date(), "1");
GelfMessage message = new GelfMessage("Short", "Long", System.currentTimeMillis(), "1");
List<byte[]> bytes = message.toDatagrams();
assertEquals(1, bytes.size());
}
Expand Down

0 comments on commit 1aa1ef2

Please sign in to comment.