Skip to content

Commit

Permalink
Allow suppressing specific fields
Browse files Browse the repository at this point in the history
Also default to omitting null values.  A configuration hook (CustomNullValue) can be used to preserve the legacy behavior
  • Loading branch information
chris-peterson committed Oct 20, 2023
1 parent 4a3c6f0 commit 056a4a3
Show file tree
Hide file tree
Showing 9 changed files with 58 additions and 12 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ Multiple providers can be provied, for example, this application uses both `Cons
### Exception Entry

> [2014-06-13 00:12:52.038Z] Application=MyApplication **Level=Error** Component=Program Operation=Main TimeElapsed=1027.0 Key=Value **ErrorReason="An exception has ocurred"** **Exception_Type=ApplicationException Exception_Message="you were unlucky!"** Exception_StackTrace=" at TestConsoleApp.Program.DoSomethingDangerous() in c:\src\git\github\chris-peterson\Spiffy\src\Tests\TestConsoleApp\Program.cs:line 47
at TestConsoleApp.Program.Main() in c:\src\git\github\chris-peterson\Spiffy\src\Tests\TestConsoleApp\Program.cs:line 29" InnermostException_Type=NullReferenceException **InnermostException_Message="Object reference not set to an instance of an object."** InnermostException_StackTrace={null} Exception="See Exception_* and InnermostException_* for more details" TimeElapsed_LongRunning=1000.0
at TestConsoleApp.Program.Main() in c:\src\git\github\chris-peterson\Spiffy\src\Tests\TestConsoleApp\Program.cs:line 29" InnermostException_Type=NullReferenceException **InnermostException_Message="Object reference not set to an instance of an object."** Exception="See Exception_* and InnermostException_* for more details" TimeElapsed_LongRunning=1000.0

## Hosting Frameworks

Expand Down
2 changes: 1 addition & 1 deletion src/Spiffy.Monitoring/BackwardsCompatabilityShims.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public static void IncludeInformationalException(this EventContext target, Excep
public static class EventContextExtensions
{
[Obsolete("This extension should be avoided, instead preferring IncludeStructure on EventContext")]
public static EventContext IncludeStructure(this EventContext eventContext, object structure, string keyPrefix = null, bool includeNullValues = true)
public static EventContext IncludeStructure(this EventContext eventContext, object structure, string keyPrefix = null, bool includeNullValues = false)
{
return eventContext.IncludeStructure(structure, keyPrefix, includeNullValues);
}
Expand Down
2 changes: 2 additions & 0 deletions src/Spiffy.Monitoring/Config/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public static void Initialize(Action<InitializationApi> customize)

_beforeLoggingActions = api.GetBeforeLoggingActions();
_loggingActions = api.GetLoggingActions();
CustomNullValue = api.CustomNullValue;
RemoveNewLines = api.RemoveNewlines;
DeprioritizedValueLength = api.DeprioritizedValueLength;
}
Expand All @@ -34,6 +35,7 @@ internal static Action<LogEvent> [] GetLoggingActions()
return _loggingActions;
}

internal static string CustomNullValue { get; set; }
internal static bool RemoveNewLines { get; private set; }

internal static int DeprioritizedValueLength { get; private set; } = 1024;
Expand Down
7 changes: 6 additions & 1 deletion src/Spiffy.Monitoring/Config/InitializationApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,12 @@ public InitializationApi()
Providers = new ProvidersApi(this);
Callbacks = new CallbacksApi(this);
}


/// <summary>
/// If set, this value is used for logging values that are null.
/// </summary>
public string CustomNullValue { get; set; }

/// <summary>
/// Whether or not to remove newline characters from logged values.
/// </summary>
Expand Down
18 changes: 15 additions & 3 deletions src/Spiffy.Monitoring/EventContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,14 @@ public void Suppress()
IsSuppressed = true;
}

public void SuppressFields(params string [] fields)
{
foreach (var field in fields)
{
_values.TryRemove(field, out _);
}
}

// ReSharper disable once RedundantDefaultMemberInitializer
volatile bool _disposed = false;

Expand Down Expand Up @@ -221,13 +229,17 @@ public void Initialize(string component, string operation)

internal LogEvent Render()
{
var kvps = _values
IEnumerable<KeyValuePair<string, (uint Order, object Value)>> values = _values;
if (Configuration.CustomNullValue == null)
{
values = values.Where(kvp => kvp.Value.Value != null);
}
var kvps = values
.OrderBy(x => x.Value.Order)
.ToDictionary(
kvp => kvp.Key,
kvp => GetValue(kvp.Value.Value));


foreach (var kvp in GetCountValues())
{
kvps.Add(kvp.Key, kvp.Value);
Expand Down Expand Up @@ -315,7 +327,7 @@ static string GetValue(object value)
{
if (value == null)
{
return "{null}";
return Configuration.CustomNullValue;
}

var str = value.ToString();
Expand Down
4 changes: 2 additions & 2 deletions src/Spiffy.Monitoring/EventContext_ObjectMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ namespace Spiffy.Monitoring
{
public partial class EventContext
{
public EventContext IncludeStructure(object structure, string keyPrefix = null, bool includeNullValues = true)
public EventContext IncludeStructure(object structure, string keyPrefix = null, bool includeNullValues = false)
{
if (structure != null)
{
foreach (var property in structure.GetType().GetTypeInfo().DeclaredProperties.Where(p => p.CanRead))
{
try
{
var val = property.GetValue(structure, null);
var val = property.GetValue(structure, null) ?? Configuration.CustomNullValue;
if (val == null && !includeNullValues)
{
continue;
Expand Down
2 changes: 1 addition & 1 deletion src/Spiffy.Monitoring/Spiffy.Monitoring.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Version>6.2.6</Version>
<Version>6.3.0</Version>
<RootNamespace>Spiffy.Monitoring</RootNamespace>
<LangVersion>latest</LangVersion>
</PropertyGroup>
Expand Down
11 changes: 8 additions & 3 deletions tests/TestConsoleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,11 @@ static void Main(string[] args)
break;
case "console":
Configuration.Initialize(spiffy => {
spiffy.CustomNullValue = "<null>";
spiffy.Callbacks.BeforeLogging(eventContext => {
if (eventContext.Level == Level.Info)
{
eventContext.Suppress();
//eventContext.Suppress();
}
});
spiffy.Providers.Console();
Expand Down Expand Up @@ -120,9 +121,13 @@ static void Main(string[] args)
// info:
using (var context = new EventContext("Greetings", "Start"))
{
context["Greeting"] = "Hello world!";
context["Greeting"] = "hi";
context["MyField"] = null;
context.SuppressFields("Greeting");
}


//return;

while (true)
{
// warning:
Expand Down
22 changes: 22 additions & 0 deletions tests/UnitTests/Publishing.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ public void Events_are_published_on_disposal()
Then(It_should_publish_the_log_message);
}

[Scenario]
public void Suppressed_fields_are_not_emitted()
{
Given(A_publishing_context)
.And(EventContext_fields_are_suppressed);
When(Disposing_an_event_context);
Then(Some_fields_are_omitted);
}

[Scenario]
public void Suppressed_events_are_not_published()
{
Expand Down Expand Up @@ -127,6 +136,13 @@ void A_publishing_context()
_context =new PublishingTestContext();
}

void EventContext_fields_are_suppressed()
{
var field = "Uninteresting";
_context.EventContext[field] = "some value";
_context.EventContext.SuppressFields(field);
}

void EventContext_is_suppressed()
{
_context.EventContext.Suppress();
Expand All @@ -144,6 +160,12 @@ void It_should_publish_the_log_message()
logEvent.MessageWithTime.Length.Should().BeInRange(10, 200);
}

void Some_fields_are_omitted()
{
var logEvent = _context.LogEvents.Single();
logEvent.Message.Should().NotContain("Uninteresting");
}

void It_should_not_publish_again()
{
_context.LogEvents.Count.Should().Be(1);
Expand Down

0 comments on commit 056a4a3

Please sign in to comment.