Skip to content

Commit e6ec554

Browse files
Configure X-Forwarded-Header in enricher registration. #11
1 parent dcdb1f3 commit e6ec554

File tree

5 files changed

+53
-44
lines changed

5 files changed

+53
-44
lines changed

src/Serilog.Enrichers.ClientInfo/Enrichers/ClientIpEnricher.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,15 +68,15 @@ private string GetIpAddress()
6868
}
6969

7070
#else
71-
private string GetIpAddress()
72-
{
73-
var ipAddress = _contextAccessor.HttpContext?.Request?.Headers["X-forwarded-for"].FirstOrDefault();
71+
private string GetIpAddress()
72+
{
73+
var ipAddress = _contextAccessor.HttpContext?.Request?.Headers[ClinetIpConfiguration.XForwardHeaderName].FirstOrDefault();
7474

75-
if (!string.IsNullOrEmpty(ipAddress))
76-
return GetIpAddressFromProxy(ipAddress);
75+
if (!string.IsNullOrEmpty(ipAddress))
76+
return GetIpAddressFromProxy(ipAddress);
7777

78-
return _contextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
79-
}
78+
return _contextAccessor.HttpContext?.Connection?.RemoteIpAddress?.ToString();
79+
}
8080
#endif
8181

8282
private string GetIpAddressFromProxy(string proxifiedIpList)
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
namespace Serilog.Enrichers
2+
{
3+
internal class ClinetIpConfiguration
4+
{
5+
public static string XForwardHeaderName { get; set; } = "X-forwarded-for";
6+
}
7+
}

src/Serilog.Enrichers.ClientInfo/Extensions/ClientInfoLoggerConfigurationExtensions.cs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,37 @@
44

55
namespace Serilog
66
{
7+
/// <summary>
8+
/// Extension methods for setting up client IP and client agent enrichers <see cref="LoggerEnrichmentConfiguration"/>.
9+
/// </summary>
710
public static class ClientInfoLoggerConfigurationExtensions
811
{
9-
public static LoggerConfiguration WithClientIp(this LoggerEnrichmentConfiguration enrichmentConfiguration)
12+
/// <summary>
13+
/// Registers the client IP enricher to enrich logs with client IP with 'X-forwarded-for' header information.
14+
/// </summary>
15+
/// <param name="enrichmentConfiguration"> The enrichment configuration. </param>
16+
/// <param name="xForwardHeaderName">
17+
/// Set the 'X-Forwarded-For' header in case if service is behind proxy server. Default value is 'X-forwarded-for'.
18+
/// </param>
19+
/// <exception cref="ArgumentNullException"> enrichmentConfiguration </exception>
20+
/// <returns> The logger configuration so that multiple calls can be chained. </returns>
21+
public static LoggerConfiguration WithClientIp(this LoggerEnrichmentConfiguration enrichmentConfiguration, string xForwardHeaderName = null)
1022
{
1123
if (enrichmentConfiguration == null)
1224
throw new ArgumentNullException(nameof(enrichmentConfiguration));
1325

26+
if (!string.IsNullOrEmpty(xForwardHeaderName))
27+
ClinetIpConfiguration.XForwardHeaderName = xForwardHeaderName;
28+
1429
return enrichmentConfiguration.With<ClientIpEnricher>();
1530
}
1631

32+
/// <summary>
33+
/// Registers the client Agent enricher to enrich logs with 'User-Agent' header information.
34+
/// </summary>
35+
/// <param name="enrichmentConfiguration"> The enrichment configuration. </param>
36+
/// <exception cref="ArgumentNullException"> enrichmentConfiguration </exception>
37+
/// <returns> The logger configuration so that multiple calls can be chained. </returns>
1738
public static LoggerConfiguration WithClientAgent(this LoggerEnrichmentConfiguration enrichmentConfiguration)
1839
{
1940
if (enrichmentConfiguration == null)

src/Serilog.Enrichers.ClientInfo/Serilog.Enrichers.ClientInfo.csproj

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<PropertyGroup>
44
<AssemblyName>Serilog.Enrichers.ClientInfo</AssemblyName>
55
<RootNamespace>Serilog</RootNamespace>
6-
<TargetFrameworks>net452;netstandard2.0;netstandard2.1</TargetFrameworks>
6+
<TargetFrameworks>net462;netstandard2.0;netstandard2.1</TargetFrameworks>
77
<LangVersion>7.3</LangVersion>
88
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
99
</PropertyGroup>
@@ -14,7 +14,7 @@
1414
<PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard2.1'">
1515
<DefineConstants>NETCORE;NETSTANDARD;NETSTANDARD2_1</DefineConstants>
1616
</PropertyGroup>
17-
<PropertyGroup Condition=" '$(TargetFramework)' == 'net452'">
17+
<PropertyGroup Condition=" '$(TargetFramework)' == 'net462'">
1818
<DefineConstants>NET45;NETFULL</DefineConstants>
1919
</PropertyGroup>
2020

@@ -26,7 +26,7 @@
2626
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
2727
<PackageReference Include="Serilog" Version="2.9.0" />
2828
</ItemGroup>
29-
<ItemGroup Condition=" '$(TargetFramework)' == 'net452'">
29+
<ItemGroup Condition=" '$(TargetFramework)' == 'net462'">
3030
<Reference Include="System.Web" />
3131
<PackageReference Include="Serilog" Version="2.4.0" />
3232
</ItemGroup>

test/Serilog.Enrichers.ClientInfo.Tests/ClientIpEnricherTests.cs

Lines changed: 14 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ public void When_Enrich_Log_Event_With_IpEnricher_AndRequest_Contain_ForwardHead
6868
{
6969
//Arrange
7070
_contextAccessor.HttpContext.Connection.RemoteIpAddress = IPAddress.Loopback;
71-
_contextAccessor.HttpContext.Request.Headers.Add("X-forwarded-for", IPAddress.Broadcast.ToString());
71+
_contextAccessor.HttpContext.Request.Headers.Add(ClinetIpConfiguration.XForwardHeaderName, IPAddress.Broadcast.ToString());
7272

7373
var ipEnricher = new ClientIpEnricher(_contextAccessor);
7474

@@ -88,48 +88,29 @@ public void When_Enrich_Log_Event_With_IpEnricher_AndRequest_Contain_ForwardHead
8888
}
8989

9090
[Fact]
91-
public void When_Enrich_Log_Event_ClientAgentEnricher_Should_Contain_ClientAgent_Property()
91+
public void When_Enrich_Log_Event_With_IpEnricher_With_Custom_XForwardHeader_AndRequest_Contain_ForwardHeader_Should_Read_ClientIp_Value_From_Header_Value()
9292
{
93-
var httpContext = new DefaultHttpContext();
94-
var contextAccessor = Substitute.For<IHttpContextAccessor>();
95-
contextAccessor.HttpContext.Returns(httpContext);
96-
97-
var agentEnricher = new ClientAgentEnricher(contextAccessor);
98-
99-
LogEvent evt = null;
100-
var log = new LoggerConfiguration()
101-
.Enrich.With(agentEnricher)
102-
.WriteTo.Sink(new DelegatingSink(e => evt = e))
103-
.CreateLogger();
104-
105-
log.Information(@"Has an Agent property");
106-
107-
Assert.NotNull(evt);
108-
Assert.True(evt.Properties.ContainsKey("ClientAgent"));
109-
Assert.True(string.IsNullOrEmpty(evt.Properties["ClientAgent"].LiteralValue().ToString()));
110-
}
111-
112-
[Fact]
113-
public void When_Enrich_Log_Event_ClientAgentEnricher_And_Request_Contain_UserAgentHeader_Should_ClientAgentProperty_Have_Value()
114-
{
115-
var httpContext = new DefaultHttpContext();
116-
httpContext.Request.Headers.Add("User-Agent", "Test Agent");
117-
var contextAccessor = Substitute.For<IHttpContextAccessor>();
118-
contextAccessor.HttpContext.Returns(httpContext);
93+
//Arrange
94+
const string customForwardHeader = "CustomForwardHeader";
95+
_contextAccessor.HttpContext.Connection.RemoteIpAddress = IPAddress.Loopback;
96+
_contextAccessor.HttpContext.Request.Headers.Add(customForwardHeader, IPAddress.Broadcast.ToString());
11997

120-
var agentEnricher = new ClientAgentEnricher(contextAccessor);
98+
var ipEnricher = new ClientIpEnricher(_contextAccessor);
99+
ClinetIpConfiguration.XForwardHeaderName = customForwardHeader;
121100

122101
LogEvent evt = null;
123102
var log = new LoggerConfiguration()
124-
.Enrich.With(agentEnricher)
103+
.Enrich.With(ipEnricher)
125104
.WriteTo.Sink(new DelegatingSink(e => evt = e))
126105
.CreateLogger();
127106

128-
log.Information(@"Has an Agent property");
107+
// Act
108+
log.Information(@"Has an IP property");
129109

110+
// Assert
130111
Assert.NotNull(evt);
131-
Assert.True(evt.Properties.ContainsKey("ClientAgent"));
132-
Assert.Equal("Test Agent", evt.Properties["ClientAgent"].LiteralValue().ToString());
112+
Assert.True(evt.Properties.ContainsKey("ClientIp"));
113+
Assert.Equal(IPAddress.Broadcast.ToString(), evt.Properties["ClientIp"].LiteralValue());
133114
}
134115
}
135116
}

0 commit comments

Comments
 (0)