Properly recognize ISO-8601 dates in Syslog events

Closes #16
This commit is contained in:
Jochen Schalanda 2016-12-21 15:58:04 +01:00
parent 6a7e4e2cf6
commit b4a32aaf80
No known key found for this signature in database
GPG Key ID: 2FC1B61A8D1F4BB0
2 changed files with 29 additions and 3 deletions

View File

@ -3,6 +3,7 @@ package org.graylog2.syslog4j.server.impl.event;
import org.graylog2.syslog4j.SyslogConstants;
import org.graylog2.syslog4j.server.SyslogServerEventIF;
import org.graylog2.syslog4j.util.SyslogUtility;
import org.joda.time.DateTime;
import java.net.InetAddress;
import java.text.DateFormat;
@ -80,6 +81,7 @@ public class SyslogServerEvent implements SyslogServerEventIF {
protected void parseDate() {
int datelength = 16;
String dateFormatS = DATE_FORMAT;
boolean isDate8601 = false;
if (this.message.length() > datelength) {
@ -89,12 +91,22 @@ public class SyslogServerEvent implements SyslogServerEventIF {
dateFormatS = DATE_FORMAT_S;
}
String year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR));
if (Character.isDigit(this.message.charAt(0))) {
datelength = this.message.indexOf(' ') + 1;
isDate8601 = true;
}
String year = Integer.toString(Calendar.getInstance().get(Calendar.YEAR));
String originalDate = this.message.substring(0, datelength - 1);
String modifiedDate = originalDate + " " + year;
String originalDate = this.message.substring(0, datelength - 1) + " " + year;
DateFormat dateFormat = new SimpleDateFormat(dateFormatS, Locale.ENGLISH);
try {
this.date = dateFormat.parse(originalDate);
if (!isDate8601) {
this.date = dateFormat.parse(modifiedDate);
} else {
this.date = DateTime.parse(originalDate).toDate();
}
this.message = this.message.substring(datelength);

View File

@ -1,6 +1,7 @@
package org.graylog2.syslog4j.server.impl.event;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Test;
import java.net.InetAddress;
@ -165,4 +166,17 @@ public class SyslogServerEventTest {
assertEquals("mymachine su[123]: 'su root' failed for lonvick on /dev/pts/8", event.getMessage());
}
@Test
public void testIssue16() throws Exception {
// Message from: https://github.com/Graylog2/syslog4j-graylog2/issues/16
final String message = "<6>2016-10-12T14:10:18Z hostname testmsg[20]: Test";
final SyslogServerEvent event = buildEvent(message);
assertEquals(new DateTime(2016, 10, 12, 14, 10, 18, DateTimeZone.UTC).toDate(), event.getDate());
assertEquals(0, event.getFacility());
assertEquals("hostname", event.getHost());
assertEquals(6, event.getLevel());
assertEquals("hostname testmsg[20]: Test", event.getMessage());
}
}