Marusyk / grok.net

.NET implementation of the grok 📝
MIT License
287 stars 55 forks source link

Changed custom pattern handling to not silently ignore errors and other minor improvements #53

Closed sandreas closed 2 years ago

sandreas commented 2 years ago

Hey there,

here is the PR you mentioned in #52.

Some notes:

public class Grok
{
    // I prefer IEnumberable over Dictionary because of thread safety
    private IEnumerable<(string, string)> _patterns;

    private Grok(string definition)
    {
        // ...
    }

    public static Grok Define(string definition)
    {
        EnsureDefintionIsValid(definition);
        return new Grok(definition);
    }

    public Grok WithPatterns(IEnumerable<(string, string)> patterns)
    {
        var patternsArray = patterns.ToArray();
        EnsurePatternsAreValid(patternsArray);
        _patterns = patternsArray;
        return this;
    }

    private void EnsurePatternsAreValid(IEnumerable<(string, string)> patterns)
    {
        // ...
    }

    private static void EnsureDefintionIsValid(string definition)
    {
        // ...
    }

    public bool TryMatch(string subject, out IEnumerable<GrokItem> matches)
    {
        matches = new List<GrokItem>();
        // ...
        return true;
    }
}

try {
  var matcher = Grok.Define("%{ZIPCODE:zipcode}:%{EMAILADDRESS:email}").WithPatterns(new[] {
      ("ZIPCODE", "[1-9]{1}[0-9]{2}\\s{0,1}[0-9]{3}"), 
      ("FLOAT", "[+-]?([0-9]*[.,])?[0-9]+"),
  });

  if(matcher.TryMatch("122 001:Bob.Davis@microsoft.com", out var matches)) {
    Console.WriteLine("Matches found: " + matches.Count);
  } else {
    Console.WriteLine("No matches found");
  };
} catch(GrokDefinitionException e) {
  Console.WriteLine("Invalid definition: " + e.Message);
} catch(GrokPatternException pe) {
  Console.WriteLine("Invalid custom pattern: " + e.Message);
}
ealvesss commented 1 year ago

Any help for first issue?

Marusyk commented 1 year ago

Hi @EltonAlvess, what do you mean? This is not an issue, it's a pull request that has already been merged