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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,8 @@ __Available properties__:
- **Options:** The [RegexOptions](https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regexoptions?view=netcore-3.1) that will be applied. Defaults to __RegexOptions.None__.
- **Timeout:** A time-out interval to evaluate regular expression. Defaults to __Regex.InfiniteMatchTimeout__.

Note that replacement also works for properties of type `IEnumerable<string>` or derived from it, for example, `string[]` or `List<string>`.

### Examples

<!-- snippet: WithRegex -->
Expand Down
27 changes: 27 additions & 0 deletions src/Destructurama.Attributed.Tests/ReplacedAttributeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ public class CustomizedRegexLogs
/// </summary>
[LogReplaced("does not matter", "does not matter")]
public int RegexReplaceForInt { get; set; }

/// <summary>
/// 123|456|789 results in "***|456|****"
/// </summary>
[LogReplaced(REGEX_WITH_VERTICAL_BARS, "***|$2|****")]
public List<string>? RegexForCollection { get; set; }
}

[TestFixture]
Expand Down Expand Up @@ -156,4 +162,25 @@ public void LogReplacedAttribute_Should_Work_Only_For_String_Properties()

props.ContainsKey("RegexReplaceForInt").ShouldBeFalse();
}

[Test]
public void LogReplacedAttribute_Should_Work_For_Collection_Of_String_Properties()
{
var customized = new CustomizedRegexLogs
{
RegexForCollection = ["123|456|789", "abc|def|ghi"]
};

var evt = DelegatingSink.Execute(customized);

var sv = (StructureValue)evt.Properties["Customized"];
var props = sv.Properties.ToDictionary(p => p.Name, p => p.Value);

props.ContainsKey("RegexForCollection").ShouldBeTrue();
var seq = props["RegexForCollection"].ShouldBeOfType<SequenceValue>();
seq.Elements.Count.ShouldBe(2);
seq.Elements[0].LiteralValue().ShouldBe("***|456|****");
seq.Elements[1].LiteralValue().ShouldBe("***|def|****");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,13 @@ public bool TryCreateLogEventProperty(string name, object? value, ILogEventPrope

if (value is string s)
{
var replacement = Regex.Replace(s, _pattern, _replacement, Options, Timeout);
property = new(name, new ScalarValue(Regex.Replace(s, _pattern, _replacement, Options, Timeout)));
return true;
}

property = new(name, new ScalarValue(replacement));
if (value is IEnumerable<string> collection)
{
property = new(name, new SequenceValue(collection.Select(s => new ScalarValue(Regex.Replace(s, _pattern, _replacement, Options, Timeout)))));
return true;
}

Expand Down
Loading