Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix issue #39. #40

Merged
merged 5 commits into from
Jul 31, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ internal ClientHeaderEnricher(IHttpContextAccessor contextAccessor)
_contextAccessor = contextAccessor;
}

/// <inheritdoc/>
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var httpContext = _contextAccessor.HttpContext;
Expand Down
19 changes: 10 additions & 9 deletions src/Serilog.Enrichers.ClientInfo/Enrichers/ClientIpEnricher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

namespace Serilog.Enrichers;

/// <inheritdoc/>
public class ClientIpEnricher : ILogEventEnricher
{
private const string IpAddressPropertyName = "ClientIp";
Expand All @@ -26,6 +27,7 @@ internal ClientIpEnricher(IHttpContextAccessor contextAccessor)
_contextAccessor = contextAccessor;
}

/// <inheritdoc/>
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var httpContext = _contextAccessor.HttpContext;
Expand All @@ -34,22 +36,21 @@ public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
return;
}

var ipAddress = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
mo-esmp marked this conversation as resolved.
Show resolved Hide resolved

if (httpContext.Items[IpAddressItemKey] is LogEventProperty logEventProperty)
{
if (!((ScalarValue)logEventProperty.Value).Value.ToString()!.Equals(ipAddress))
{
logEventProperty = new LogEventProperty(IpAddressPropertyName, new ScalarValue(ipAddress));
}

logEvent.AddPropertyIfAbsent(logEventProperty);
return;
}

var ipAddress = _contextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();

if (string.IsNullOrWhiteSpace(ipAddress))
{
ipAddress = "unknown";
}

var ipAddressProperty = new LogEventProperty(IpAddressPropertyName, new ScalarValue(ipAddress));
LogEventProperty ipAddressProperty = new(IpAddressPropertyName, new ScalarValue(ipAddress));
httpContext.Items.Add(IpAddressItemKey, ipAddressProperty);

logEvent.AddPropertyIfAbsent(ipAddressProperty);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ public ClientHeaderEnricherTests()
_contextAccessor = Substitute.For<IHttpContextAccessor>();
_contextAccessor.HttpContext.Returns(httpContext);
}

[Fact]
public void EnrichLogWithClientHeader_WhenHttpRequestContainHeader_ShouldCreateNamedHeaderValueProperty()
{
// Arrange
var headerKey = "RequestId";
var propertyName = "HttpRequestId";
var headerValue = Guid.NewGuid().ToString();
_contextAccessor.HttpContext.Request.Headers.Add(headerKey, headerValue);
_contextAccessor.HttpContext!.Request!.Headers[headerKey] = headerValue;

var clientHeaderEnricher = new ClientHeaderEnricher(headerKey, propertyName, _contextAccessor);

Expand All @@ -35,8 +35,8 @@ public void EnrichLogWithClientHeader_WhenHttpRequestContainHeader_ShouldCreateN
.CreateLogger();

// Act
log.Information(@"First testing log enricher.");
log.Information(@"Second testing log enricher.");
log.Information("First testing log enricher.");
log.Information("Second testing log enricher.");

// Assert
Assert.NotNull(evt);
Expand All @@ -50,9 +50,9 @@ public void EnrichLogWithClientHeader_WhenHttpRequestContainHeader_ShouldCreateH
// Arrange
var headerKey = "RequestId";
var headerValue = Guid.NewGuid().ToString();
_contextAccessor.HttpContext.Request.Headers.Add(headerKey, headerValue);
_contextAccessor!.HttpContext!.Request!.Headers[headerKey] = headerValue;

var clientHeaderEnricher = new ClientHeaderEnricher(headerKey, propertyName:string.Empty, _contextAccessor);
var clientHeaderEnricher = new ClientHeaderEnricher(headerKey, propertyName: string.Empty, _contextAccessor);

LogEvent evt = null;
var log = new LoggerConfiguration()
Expand All @@ -61,8 +61,8 @@ public void EnrichLogWithClientHeader_WhenHttpRequestContainHeader_ShouldCreateH
.CreateLogger();

// Act
log.Information(@"First testing log enricher.");
log.Information(@"Second testing log enricher.");
log.Information("First testing log enricher.");
log.Information("Second testing log enricher.");

// Assert
Assert.NotNull(evt);
Expand All @@ -71,18 +71,17 @@ public void EnrichLogWithClientHeader_WhenHttpRequestContainHeader_ShouldCreateH
}

[Fact]
public void EnrichLogWithMulitpleClientHeaderEnricher_WhenHttpRequestContainHeaders_ShouldCreateHeaderValuesProperty()
public void EnrichLogWithMultipleClientHeaderEnricher_WhenHttpRequestContainHeaders_ShouldCreateHeaderValuesProperty()
{
// Arrange
var headerKey1 = "Header1";
var headerKey2 = "User-Agent";
var headerValue1 = Guid.NewGuid().ToString();
var headerValue2 = Guid.NewGuid().ToString();
_contextAccessor.HttpContext.Request.Headers.Add(headerKey1, headerValue1);
_contextAccessor.HttpContext.Request.Headers.Add(headerKey2, headerValue2);

var clientHeaderEnricher1 = new ClientHeaderEnricher(headerKey1, propertyName:string.Empty, _contextAccessor);
var clientHeaderEnricher2 = new ClientHeaderEnricher(headerKey2, propertyName:string.Empty, _contextAccessor);
_contextAccessor!.HttpContext!.Request!.Headers[headerKey1] = headerValue1;
_contextAccessor!.HttpContext!.Request!.Headers[headerKey2] = headerValue2;
var clientHeaderEnricher1 = new ClientHeaderEnricher(headerKey1, propertyName: string.Empty, _contextAccessor);
var clientHeaderEnricher2 = new ClientHeaderEnricher(headerKey2, propertyName: string.Empty, _contextAccessor);

LogEvent evt = null;
var log = new LoggerConfiguration()
Expand All @@ -92,8 +91,8 @@ public void EnrichLogWithMulitpleClientHeaderEnricher_WhenHttpRequestContainHead
.CreateLogger();

// Act
log.Information(@"First testing log enricher.");
log.Information(@"Second testing log enricher.");
log.Information("First testing log enricher.");
log.Information("Second testing log enricher.");

// Assert
Assert.NotNull(evt);
Expand All @@ -108,7 +107,7 @@ public void EnrichLogWithClientHeader_WhenHttpRequestNotContainHeader_ShouldCrea
{
// Arrange
var headerKey = "RequestId";
var clientHeaderEnricher = new ClientHeaderEnricher(headerKey, propertyName:string.Empty, _contextAccessor);
var clientHeaderEnricher = new ClientHeaderEnricher(headerKey, propertyName: string.Empty, _contextAccessor);

LogEvent evt = null;
var log = new LoggerConfiguration()
Expand All @@ -117,8 +116,8 @@ public void EnrichLogWithClientHeader_WhenHttpRequestNotContainHeader_ShouldCrea
.CreateLogger();

// Act
log.Information(@"First testing log enricher.");
log.Information(@"Second testing log enricher.");
log.Information("First testing log enricher.");
log.Information("Second testing log enricher.");

// Assert
Assert.NotNull(evt);
Expand All @@ -132,7 +131,7 @@ public void WithRequestHeader_ThenLoggerIsCalled_ShouldNotThrowException()
// Arrange
var logger = new LoggerConfiguration()
.Enrich.WithRequestHeader("HeaderName")
.WriteTo.Sink(new DelegatingSink(e => { }))
.WriteTo.Sink(new DelegatingSink(_ => { }))
.CreateLogger();

// Act
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Serilog.Enrichers.ClientInfo.Tests;

public class ClientIpEnricherIntegrationTests(CustomWebApplicationFactory factory) : IClassFixture<CustomWebApplicationFactory>
{
[Fact]
public async Task GetRoot_ReturnsHelloWorld()
{
// Arrange
const string ip = "1.2.3.4";

var client = factory.CreateClient();
client.DefaultRequestHeaders.Add("x-forwarded-for", ip);

// Act
var response = await client.GetAsync("/");
var logs = DelegatingSink.Logs;
var allClientIpLogs = logs
.SelectMany(l => l.Properties)
.Where(p => p.Key == "ClientIp")
.ToList();
var forwardedClientIpLogs = logs
.SelectMany(l => l.Properties)
.Where(p => p.Key == "ClientIp" && p.Value.LiteralValue().Equals(ip))
.ToList();

// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(forwardedClientIpLogs.Count, allClientIpLogs.Count - 1);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void EnrichLogWithClientIp_ShouldCreateClientIpPropertyWithValue(string i
{
// Arrange
var ipAddress = IPAddress.Parse(ip);
_contextAccessor.HttpContext.Connection.RemoteIpAddress = ipAddress;
_contextAccessor.HttpContext!.Connection.RemoteIpAddress = ipAddress;

var ipEnricher = new ClientIpEnricher(_contextAccessor);

Expand Down Expand Up @@ -74,7 +74,7 @@ public void WithClientIp_ThenLoggerIsCalled_ShouldNotThrowException()
// Arrange
var logger = new LoggerConfiguration()
.Enrich.WithClientIp()
.WriteTo.Sink(new DelegatingSink(e => { }))
.WriteTo.Sink(new DelegatingSink(_ => { }))
.CreateLogger();

// Act
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public void EnrichLogWithCorrelationId_WhenHttpRequestContainCorrelationHeader_S
{
// Arrange
var correlationId = Guid.NewGuid().ToString();
_contextAccessor.HttpContext.Request.Headers.Add(HeaderKey, correlationId);
_contextAccessor.HttpContext!.Request!.Headers[HeaderKey] = correlationId;
var correlationIdEnricher = new CorrelationIdEnricher(HeaderKey, false, _contextAccessor);

LogEvent evt = null;
Expand All @@ -47,8 +47,7 @@ public void EnrichLogWithCorrelationId_WhenHttpRequestContainCorrelationHeader_S
{
// Arrange
var correlationId = Guid.NewGuid().ToString();
_contextAccessor.HttpContext.Request.Headers.Add(HeaderKey, correlationId);

_contextAccessor.HttpContext!.Request!.Headers[HeaderKey] = correlationId;
var correlationIdEnricher = new CorrelationIdEnricher(HeaderKey, false, _contextAccessor);

LogEvent evt = null;
Expand Down Expand Up @@ -113,7 +112,7 @@ public void EnrichLogWithCorrelationId_WhenHttpResponseContainsCorrelationIdHead
{
// Arrange
var correlationId = Guid.NewGuid().ToString();
_contextAccessor.HttpContext.Response.Headers.Add(HeaderKey, correlationId);
_contextAccessor.HttpContext!.Request!.Headers[HeaderKey] = correlationId;
var correlationIdEnricher = new CorrelationIdEnricher(HeaderKey, false, _contextAccessor);

LogEvent evt = null;
Expand All @@ -137,8 +136,8 @@ public void EnrichLogWithCorrelationId_WhenHttpRequestAndResponseContainCorrelat
// Arrange
var requestCorrelationId = Guid.NewGuid().ToString();
var responseCorrelationId = Guid.NewGuid().ToString();
_contextAccessor.HttpContext.Request.Headers.Add(HeaderKey, requestCorrelationId);
_contextAccessor.HttpContext.Response.Headers.Add(HeaderKey, responseCorrelationId);
_contextAccessor.HttpContext!.Request!.Headers[HeaderKey] = requestCorrelationId;
_contextAccessor.HttpContext!.Response!.Headers[HeaderKey] = responseCorrelationId;
var correlationIdEnricher = new CorrelationIdEnricher(HeaderKey, false, _contextAccessor);

LogEvent evt = null;
Expand All @@ -162,7 +161,7 @@ public void WithClientIp_ThenLoggerIsCalled_ShouldNotThrowException()
// Arrange
var logger = new LoggerConfiguration()
.Enrich.WithCorrelationId()
.WriteTo.Sink(new DelegatingSink(e => { }))
.WriteTo.Sink(new DelegatingSink(_ => { }))
.CreateLogger();

// Act
Expand Down
28 changes: 10 additions & 18 deletions test/Serilog.Enrichers.ClientInfo.Tests/DelegatingSink.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,24 @@
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Generic;

namespace Serilog.Enrichers.ClientInfo.Tests;

public class DelegatingSink : ILogEventSink
public class DelegatingSink(Action<LogEvent> write, bool saveLogs = false) : ILogEventSink
{
private readonly Action<LogEvent> _write;
private static readonly List<LogEvent> LogsEvents = new();
private readonly Action<LogEvent> _write = write ?? throw new ArgumentNullException(nameof(write));

public DelegatingSink(Action<LogEvent> write)
{
_write = write ?? throw new ArgumentNullException(nameof(write));
}
public static IReadOnlyList<LogEvent> Logs => LogsEvents;

public void Emit(LogEvent logEvent)
{
_write(logEvent);
}
if (saveLogs)
{
LogsEvents.Add(logEvent);
}

public static LogEvent GetLogEvent(Action<ILogger> writeAction)
{
LogEvent result = null;
var l = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.Sink(new DelegatingSink(le => result = le))
.CreateLogger();

writeAction(l);
return result;
_write(logEvent);
}
}
5 changes: 1 addition & 4 deletions test/Serilog.Enrichers.ClientInfo.Tests/Extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,5 @@ namespace Serilog.Enrichers.ClientInfo.Tests;

internal static class Extensions
{
public static object LiteralValue(this LogEventPropertyValue @this)
{
return ((ScalarValue)@this).Value;
}
public static object LiteralValue(this LogEventPropertyValue @this) => ((ScalarValue)@this).Value;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.7" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
<PackageReference Include="nsubstitute" Version="5.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.1" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using System.IO;

namespace Serilog.Enrichers.ClientInfo.Tests;

public class CustomWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseContentRoot(Directory.GetCurrentDirectory());
}
}
41 changes: 41 additions & 0 deletions test/Serilog.Enrichers.ClientInfo.Tests/TestSetup/WebApi.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Enrichers.ClientInfo.Tests;
using Serilog.Events;

Log.Logger = new LoggerConfiguration()
.Enrich.WithClientIp()
.Enrich.WithRequestHeader("X-Forwarded-For")
.WriteTo.Sink(new DelegatingSink(e => LogEvent = e, saveLogs: true))
.CreateLogger();

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();
builder.Services
.AddHttpContextAccessor()
.Configure<ForwardedHeadersOptions>(
options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});

var app = builder.Build();

app.UseForwardedHeaders();

app.MapGet("/", () => "hello world");

app.Run();

public partial class Program
{
private Program()
{ }

public static LogEvent LogEvent;
}
Loading