Skip to content
Merged
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
4 changes: 3 additions & 1 deletion src/Grok.Net.Tests/Patterns/grok-custom-patterns
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
ZIPCODE [1-9]{1}[0-9]{2}\s{0,1}[0-9]{3}
ZIPCODE [1-9]{1}[0-9]{2}\s{0,1}[0-9]{3}
WRONGPATTERN1 \\\\\
WRONGPATTERN2 \\\\\
25 changes: 25 additions & 0 deletions src/Grok.Net.Tests/UnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -189,5 +189,30 @@ public void LoadCustomPatterns(string zipcode)
Assert.Equal(zipcode, grokResult[0].Value);
Assert.Equal(email, grokResult[1].Value);
}

[Fact]
public void LoadWrongCustomPatterns()
{
// Arrange
const string client = "192.168.1.1";
const string duration = "1";

var sut = new Grok("%{WRONGPATTERN1:duration}:%{WRONGPATTERN2:client}");

try
{
// Act
var grokResult = sut.Parse($"{duration}:{client}");

// Assert (checks if regex is invalid)
Assert.Equal("", grokResult[0].Value);
Assert.Equal("", grokResult[1].Value);
}
catch
{
// Assert (checks if pattern is invalid)
Assert.Throws<System.FormatException>(() => sut.Parse($"{duration}:{client}"));
}
}
}
}
13 changes: 13 additions & 0 deletions src/Grok.Net/Grok.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,23 @@ private void ProcessPatternLine(string line)
}

string[] strArray = line.Split(new[] { ' ' }, 2);
if (strArray.Length != 2)
{
throw new FormatException("Custom pattern was not in a correct form");
}

if (strArray[0].Equals("#", StringComparison.OrdinalIgnoreCase))
{
return;
}
try
{
Regex.Match("", strArray[1]);
}
catch
{
return;
}

// check before adding to avoid an exception in case the same pattern is present in the custom patterns file.
if (!_patterns.ContainsKey(strArray[0]))
Expand Down