diff --git a/loggly-client/src/main/java/com/github/tony19/loggly/LogglyClient.java b/loggly-client/src/main/java/com/github/tony19/loggly/LogglyClient.java index bab4f33..9a43def 100644 --- a/loggly-client/src/main/java/com/github/tony19/loggly/LogglyClient.java +++ b/loggly-client/src/main/java/com/github/tony19/loggly/LogglyClient.java @@ -80,7 +80,7 @@ public void setTags(String... tags) { if (!first) { builder.append(","); } - builder.append(t); + builder.append(sanitizeTag(t)); } first = false; } @@ -212,4 +212,24 @@ private String joinStrings(Collection messages) { } return b.toString(); } + + /** + * Sanitize the tag based on the restrictions described in + * https://www.loggly.com/docs/tags/. + * Sanitation works by replacing invalid characters with the _ (underscore) character. + * + * @param tag tag to be sanitized + * @return the tag without invalid characters + */ + private String sanitizeTag(String tag) { + // replace invalid characters with _ + tag = tag.replaceAll("[^A-Za-z0-9_*,.\\-]", "_"); + + // don't allow non-alphanumeric values starting the tag + if (Character.isLetterOrDigit(tag.charAt(0))) { + return tag; + } + + return tag.substring(1); + } } diff --git a/loggly-client/src/test/java/com/github/tony19/loggly/LogglyClientTest.java b/loggly-client/src/test/java/com/github/tony19/loggly/LogglyClientTest.java index f694a8b..6a88f0d 100644 --- a/loggly-client/src/test/java/com/github/tony19/loggly/LogglyClientTest.java +++ b/loggly-client/src/test/java/com/github/tony19/loggly/LogglyClientTest.java @@ -15,18 +15,19 @@ */ package com.github.tony19.loggly; -import retrofit2.Call; import org.junit.Before; import org.junit.Rule; -import org.junit.rules.ExpectedException; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; -import static org.junit.Assert.assertThat; +import retrofit2.Call; + import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.mock; @@ -138,4 +139,18 @@ public void emptyTagsResultInNoTags() { loggly.logBulk("event"); Mockito.verify(restApi).logBulk(TOKEN, NO_TAGS, "event\n"); } + + @Test + public void invalidTagsResultInNoTags() { + loggly.setTags("", " ", " ,", ", , ,, "); + loggly.logBulk("event"); + Mockito.verify(restApi).logBulk(TOKEN, NO_TAGS, "event\n"); + } + + @Test + public void invalidTagsAreSentToLogglySanitized() { + loggly.setTags("_startInvalid", "middle@invalid.com", "%how_many$*3"); + loggly.logBulk("event"); + Mockito.verify(restApi).logBulk(TOKEN, "startInvalid,middle_invalid.com,how_many_*3", "event\n"); + } }