Skip to content
This repository was archived by the owner on Oct 2, 2024. It is now read-only.

Commit d32c124

Browse files
authored
Merge pull request #53 from dgarciarubio/app-settings
Add extension methods for each enricher in order to add App settings support
2 parents e351772 + 4835a75 commit d32c124

File tree

8 files changed

+252
-22
lines changed

8 files changed

+252
-22
lines changed

README.md

Lines changed: 39 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,28 +16,28 @@ When you work with an ASP.NET web application, this package adds
1616
When working with ASP.NET MVC (not Core) or ASP.NET Web API, you may also want to have a look at [SerilogWeb.Classic.Mvc](https://github.com/serilog-web/classic-mvc) and [SerilogWeb.Classic.WebAPI](https://github.com/serilog-web/classic-webapi)
1717

1818
## Enrichers
19-
The following enrichers are available in the `SerilogWeb.Classic.Enrichers` namespace:
20-
21-
* **ClaimValueEnricher** : adds a property contaning the value of a given claim from the current `ClaimsIdentity` User
22-
* **HttpRequestClientHostIPEnricher** : adds a property `HttpRequestClientHostIP` containing `Request.UserHostAddress` (optionally checking for proxy header)
23-
* **HttpRequestClientHostNameEnricher** : adds a property `HttpRequestClientHostName` containing `Request.UserHostName`
24-
* **HttpRequestIdEnricher** : adds a property `HttpRequestId` with a GUID used to identify requests.
25-
* **HttpRequestNumberEnricher** : adds a property `HttpRequestNumber` with an incrementing number per request.
26-
* **HttpRequestRawUrlEnricher** : adds a property `HttpRequestRawUrl` with the Raw Url of the Request.
27-
* **HttpRequestTraceIdEnricher** : adds a property `HttpRequestTraceId` with a GUID matching the RequestTraceIdentifier assigned by IIS and used throughout ASP.NET/ETW. (IIS ETW tracing must be enabled for this to work)
28-
* **HttpRequestTypeEnricher** : adds a property `HttpRequestType` with the Request Type (`GET` or `POST`).
29-
* **HttpRequestUrlEnricher** : adds a property `HttpRequestUrl` with the Url of the Request.
30-
* **HttpRequestUrlReferrerEnricher** : adds a property `HttpRequestUrlReferrer` with the UrlReferrer of the Request.
31-
* **HttpRequestUserAgentEnricher** : adds a property `HttpRequestUserAgent` with the User Agent of the Request.
32-
* **HttpSessionIdEnricher** : adds a property `HttpSessionId` with the current ASP.NET session id.
33-
* **UserNameEnricher** : adds a property `UserName` with the current username or, when anonymous, a defined value. By default this is set to _(anonymous)_.
19+
The following enrichers are available as extension methods from the `LoggerConfiguration.Enrich` API:
20+
21+
* **WithClaimValue** : adds a property contaning the value of a given claim from the current `ClaimsIdentity` User
22+
* **WithHttpRequestClientHostIP** : adds a property `HttpRequestClientHostIP` containing `Request.UserHostAddress` (optionally checking for proxy header)
23+
* **WithHttpRequestClientHostName** : adds a property `HttpRequestClientHostName` containing `Request.UserHostName`
24+
* **WithHttpRequestId** : adds a property `HttpRequestId` with a GUID used to identify requests.
25+
* **WithHttpRequestNumber** : adds a property `HttpRequestNumber` with an incrementing number per request.
26+
* **WithHttpRequestRawUrl** : adds a property `HttpRequestRawUrl` with the Raw Url of the Request.
27+
* **WithHttpRequestTraceId** : adds a property `HttpRequestTraceId` with a GUID matching the RequestTraceIdentifier assigned by IIS and used throughout ASP.NET/ETW. (IIS ETW tracing must be enabled for this to work)
28+
* **WithHttpRequestType** : adds a property `HttpRequestType` with the Request Type (`GET` or `POST`).
29+
* **WithHttpRequestUrl** : adds a property `HttpRequestUrl` with the Url of the Request.
30+
* **WithHttpRequestUrlReferrer** : adds a property `HttpRequestUrlReferrer` with the UrlReferrer of the Request.
31+
* **WithHttpRequestUserAgent** : adds a property `HttpRequestUserAgent` with the User Agent of the Request.
32+
* **WithHttpSessionId** : adds a property `HttpSessionId` with the current ASP.NET session id.
33+
* **WithUserName** : adds a property `UserName` with the current username or, when anonymous, a defined value. By default this is set to _(anonymous)_.
3434

3535

3636
```csharp
3737
var log = new LoggerConfiguration()
3838
.WriteTo.Console()
39-
.Enrich.With<HttpRequestIdEnricher>()
40-
.Enrich.With<UserNameEnricher>()
39+
.Enrich.WithHttpRequestId()
40+
.Enrich.WithUserName()
4141
.CreateLogger();
4242
```
4343

@@ -46,10 +46,31 @@ To override the username enricher behaviour:
4646
```csharp
4747
var log = new LoggerConfiguration()
4848
.WriteTo.ColoredConsole()
49-
.Enrich.With(new UserNameEnricher("not known yet", System.Environment.UserName))
49+
.Enrich.WithUserName("not known yet", System.Environment.UserName)
5050
.CreateLogger();
5151
```
5252

53+
Enrichers can also be defined in a configuration file by using [Serilog.Settings.AppSettings](https://github.com/serilog/serilog-settings-appsettings) as follows:
54+
55+
```xml
56+
<appSettings>
57+
<add key="serilog:using:SerilogWeb.Classic" value="SerilogWeb.Classic"/>
58+
<add key="serilog:enrich:WithClaimValue.claimProperty" value="MyClaimPropertyName"/>
59+
<add key="serilog:enrich:WithHttpRequestClientHostIP"/>
60+
<add key="serilog:enrich:WithHttpRequestClientHostName"/>
61+
<add key="serilog:enrich:WithHttpRequestId"/>
62+
<add key="serilog:enrich:WithHttpRequestNumber"/>
63+
<add key="serilog:enrich:WithHttpRequestRawUrl"/>
64+
<add key="serilog:enrich:WithHttpRequestTraceId"/>
65+
<add key="serilog:enrich:WithHttpRequestType"/>
66+
<add key="serilog:enrich:WithHttpRequestUrl"/>
67+
<add key="serilog:enrich:WithHttpRequestUrlReferrer"/>
68+
<add key="serilog:enrich:WithHttpRequestUserAgent"/>
69+
<add key="serilog:enrich:WithHttpSessionId"/>
70+
<add key="serilog:enrich:WithUserName"/>
71+
</appSettings>
72+
```
73+
5374
## HttpModule
5475
The **ApplicationLifecycleModule** *Http module* is automatically hooked up into your ASP.NET application as soon as you install the *SerilogWeb.Classic* package.
5576

src/SerilogWeb.Classic/Classic/Enrichers/ClaimValueEnricher.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@ public ClaimValueEnricher()
4040

4141
/// <summary>
4242
/// Initializes a new instance of the <see cref="ClaimValueEnricher"/> class.
43-
/// <param name="claimProperty">The claim property name searched for value to enrich log events.</param>
4443
/// </summary>
44+
/// <param name="claimProperty">The claim property name searched for value to enrich log events.</param>
4545
public ClaimValueEnricher(string claimProperty) : this(claimProperty, null)
4646
{
4747
_claimProperty = claimProperty;

src/SerilogWeb.Classic/SerilogWeb.Classic.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
<ItemGroup>
5656
<Compile Include="Classic\ApplicationLifecycleModule.cs" />
5757
<Compile Include="Classic\SerilogWebClassicConfigurationBuilder.cs" />
58+
<Compile Include="SerilogWebClassicLoggerConfigurationExtensions.cs" />
5859
<Compile Include="Classic\WebRequestLoggingHandler.cs" />
5960
<Compile Include="Classic\Enrichers\ClaimValueEnricher.cs" />
6061
<Compile Include="Classic\Enrichers\HttpContextCurrent.cs" />
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
using Serilog.Configuration;
2+
using Serilog.Core;
3+
using SerilogWeb.Classic.Enrichers;
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Linq;
7+
using System.Text;
8+
using System.Threading.Tasks;
9+
10+
namespace Serilog
11+
{
12+
/// <summary>
13+
/// Extends <see cref="LoggerConfiguration"/> to add enrichers for SerilogWeb.Classic's logging module
14+
/// </summary>
15+
public static class SerilogWebClassicLoggerConfigurationExtensions
16+
{
17+
/// <summary>
18+
/// Enrich log events with the named Claim Value.
19+
/// </summary>
20+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
21+
/// <param name="claimProperty">The claim property name searched for value to enrich log events.</param>
22+
/// <param name="logEventProperty">The property name added to enriched log events. Leave null (default) to use the claim property name.</param>
23+
/// <returns>Configuration object allowing method chaining.</returns>
24+
public static LoggerConfiguration WithClaimValue(
25+
this LoggerEnrichmentConfiguration enrichmentConfiguration,
26+
string claimProperty,
27+
string logEventProperty = null)
28+
{
29+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
30+
return enrichmentConfiguration.With(new ClaimValueEnricher(claimProperty, logEventProperty));
31+
}
32+
33+
/// <summary>
34+
/// Enrich log events with the Client IP Address.
35+
/// </summary>
36+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
37+
/// <param name="checkForHttpProxies">if set to <c>true</c> this Enricher also checks for HTTP proxies and their X-FORWARDED-FOR header.</param>
38+
/// <returns>Configuration object allowing method chaining.</returns>
39+
public static LoggerConfiguration WithHttpRequestClientHostIP(
40+
this LoggerEnrichmentConfiguration enrichmentConfiguration,
41+
bool checkForHttpProxies = true)
42+
{
43+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
44+
return enrichmentConfiguration.With(new HttpRequestClientHostIPEnricher(checkForHttpProxies));
45+
}
46+
47+
/// <summary>
48+
/// Enrich log events with the Client Host Name.
49+
/// </summary>
50+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
51+
/// <returns>Configuration object allowing method chaining.</returns>
52+
public static LoggerConfiguration WithHttpRequestClientHostName(
53+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
54+
{
55+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
56+
return enrichmentConfiguration.With<HttpRequestClientHostNameEnricher>();
57+
}
58+
59+
/// <summary>
60+
/// Enrich log events with a HttpRequestId GUID.
61+
/// </summary>
62+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
63+
/// <returns>Configuration object allowing method chaining.</returns>
64+
public static LoggerConfiguration WithHttpRequestId(
65+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
66+
{
67+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
68+
return enrichmentConfiguration.With<HttpRequestIdEnricher>();
69+
}
70+
71+
/// <summary>
72+
/// Enrich log events with a HttpRequestNumber unique within the current
73+
/// logging session.
74+
/// </summary>
75+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
76+
/// <returns>Configuration object allowing method chaining.</returns>
77+
public static LoggerConfiguration WithHttpRequestNumber(
78+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
79+
{
80+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
81+
return enrichmentConfiguration.With<HttpRequestNumberEnricher>();
82+
}
83+
84+
/// <summary>
85+
/// Enrich log events with the Url of the Request.
86+
/// </summary>
87+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
88+
/// <returns>Configuration object allowing method chaining.</returns>
89+
public static LoggerConfiguration WithHttpRequestUrl(
90+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
91+
{
92+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
93+
return enrichmentConfiguration.With< HttpRequestUrlEnricher>();
94+
}
95+
96+
/// <summary>
97+
/// Enrich log events with the Raw Url of the Request.
98+
/// </summary>
99+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
100+
/// <returns>Configuration object allowing method chaining.</returns>
101+
public static LoggerConfiguration WithHttpRequestRawUrl(
102+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
103+
{
104+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
105+
return enrichmentConfiguration.With<HttpRequestRawUrlEnricher>();
106+
}
107+
108+
/// <summary>
109+
/// Enrich log events with a HttpRequestTraceId GUID matching the
110+
/// RequestTraceIdentifier assigned by IIS and used throughout
111+
/// ASP.NET/ETW. IIS ETW tracing must be enabled for this to work.
112+
/// </summary>
113+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
114+
/// <returns>Configuration object allowing method chaining.</returns>
115+
public static LoggerConfiguration WithHttpRequestTraceId(
116+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
117+
{
118+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
119+
return enrichmentConfiguration.With<HttpRequestTraceIdEnricher>();
120+
}
121+
122+
/// <summary>
123+
/// Enrich log events with the HTTP Request Type.
124+
/// </summary>
125+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
126+
/// <returns>Configuration object allowing method chaining.</returns>
127+
public static LoggerConfiguration WithHttpRequestType(
128+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
129+
{
130+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
131+
return enrichmentConfiguration.With<HttpRequestTypeEnricher>();
132+
}
133+
134+
/// <summary>
135+
/// Enrich log events with the Url of the Referrer.
136+
/// </summary>
137+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
138+
/// <returns>Configuration object allowing method chaining.</returns>
139+
public static LoggerConfiguration WithHttpRequestUrlReferrer(
140+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
141+
{
142+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
143+
return enrichmentConfiguration.With<HttpRequestUrlReferrerEnricher>();
144+
}
145+
146+
/// <summary>
147+
/// Enrich log events with the Client User Agent.
148+
/// </summary>
149+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
150+
/// <returns>Configuration object allowing method chaining.</returns>
151+
public static LoggerConfiguration WithHttpRequestUserAgent(
152+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
153+
{
154+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
155+
return enrichmentConfiguration.With<HttpRequestUserAgentEnricher>();
156+
}
157+
158+
/// <summary>
159+
/// Enrich log events with the HttpSessionId property.
160+
/// </summary>
161+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
162+
/// <returns>Configuration object allowing method chaining.</returns>
163+
public static LoggerConfiguration WithHttpSessionId(
164+
this LoggerEnrichmentConfiguration enrichmentConfiguration)
165+
{
166+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
167+
return enrichmentConfiguration.With<HttpSessionIdEnricher>();
168+
}
169+
170+
/// <summary>
171+
/// Enrich log events with the UserName property when available in the HttpContext.
172+
/// </summary>
173+
/// <param name="enrichmentConfiguration">Logger enrichment configuration.</param>
174+
/// <param name="anonymousUsername">The anonymous username. Leave null if you do not want to use anonymous user names. By default it is (anonymous).</param>
175+
/// <param name="noneUsername">The none username. If there is no username to be found, it will output this username. Leave null (default) to ignore non usernames.</param>
176+
/// <returns>Configuration object allowing method chaining.</returns>
177+
public static LoggerConfiguration WithUserName(
178+
this LoggerEnrichmentConfiguration enrichmentConfiguration,
179+
string anonymousUsername = "(anonymous)",
180+
string noneUsername = null)
181+
{
182+
if (enrichmentConfiguration == null) throw new ArgumentNullException(nameof(enrichmentConfiguration));
183+
return enrichmentConfiguration.With(new UserNameEnricher(anonymousUsername, noneUsername));
184+
}
185+
}
186+
}

test/SerilogWeb.Test/Global.asax.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,9 @@ protected void Application_Start(object sender, EventArgs e)
1616
.AtLevel(LogEventLevel.Debug)
1717
.OnMatch(ctx => ctx.Response.StatusCode >= 400))
1818
);
19-
19+
2020
Log.Logger = new LoggerConfiguration()
21-
.MinimumLevel.Debug()
22-
.WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}")
21+
.ReadFrom.AppSettings()
2322
.CreateLogger();
2423
}
2524
}

test/SerilogWeb.Test/SerilogWeb.Test.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@
5252
<Reference Include="Serilog, Version=2.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10, processorArchitecture=MSIL">
5353
<HintPath>..\..\packages\Serilog.2.6.0\lib\net45\Serilog.dll</HintPath>
5454
</Reference>
55+
<Reference Include="Serilog.Settings.AppSettings, Version=2.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10, processorArchitecture=MSIL">
56+
<HintPath>..\..\packages\Serilog.Settings.AppSettings.2.1.2\lib\net45\Serilog.Settings.AppSettings.dll</HintPath>
57+
</Reference>
5558
<Reference Include="Serilog.Sinks.Trace, Version=2.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10, processorArchitecture=MSIL">
5659
<HintPath>..\..\packages\Serilog.Sinks.Trace.2.1.0\lib\net45\Serilog.Sinks.Trace.dll</HintPath>
5760
</Reference>

test/SerilogWeb.Test/Web.config

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,25 @@
44
http://go.microsoft.com/fwlink/?LinkId=169433
55
-->
66
<configuration>
7+
<appSettings>
8+
<add key="serilog:minimum-level" value="Debug" />
9+
<add key="serilog:using:Trace" value="Serilog.Sinks.Trace" />
10+
<add key="serilog:write-to:Trace"/>
11+
<add key="serilog:write-to:Trace.outputTemplate" value="{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}"/>
12+
<add key="serilog:using:SerilogWeb.Classic" value="SerilogWeb.Classic"/>
13+
<add key="serilog:enrich:WithHttpRequestClientHostIP"/>
14+
<add key="serilog:enrich:WithHttpRequestClientHostName"/>
15+
<add key="serilog:enrich:WithHttpRequestId"/>
16+
<add key="serilog:enrich:WithHttpRequestNumber"/>
17+
<add key="serilog:enrich:WithHttpRequestRawUrl"/>
18+
<add key="serilog:enrich:WithHttpRequestUrl"/>
19+
<add key="serilog:enrich:WithHttpRequestUrlReferrer"/>
20+
<add key="serilog:enrich:WithHttpRequestUserAgent"/>
21+
<add key="serilog:enrich:WithHttpRequestTraceId"/>
22+
<add key="serilog:enrich:WithHttpRequestType"/>
23+
<add key="serilog:enrich:WithHttpSessionId"/>
24+
<add key="serilog:enrich:WithUserName"/>
25+
</appSettings>
726
<system.web>
827
<compilation debug="true" targetFramework="4.5.1" />
928
<httpRuntime targetFramework="4.5.1" />

test/SerilogWeb.Test/packages.config

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@
33
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net451" />
44
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net451" developmentDependency="true" />
55
<package id="Serilog" version="2.6.0" targetFramework="net451" />
6+
<package id="Serilog.Settings.AppSettings" version="2.1.2" targetFramework="net451" />
67
<package id="Serilog.Sinks.Trace" version="2.1.0" targetFramework="net451" />
78
</packages>

0 commit comments

Comments
 (0)