Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitcd2a857

Browse files
authored
Merge pull request#305 from dnperfors/issue174-configurable-properties
Add GetMessageTemplateProperties to options
2 parents1d99211 +ccd73c3 commitcd2a857

File tree

3 files changed

+51
-8
lines changed

3 files changed

+51
-8
lines changed

‎src/Serilog.AspNetCore/AspNetCore/RequestLoggingMiddleware.cs‎

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
usingSerilog.Extensions.Hosting;
1919
usingSerilog.Parsing;
2020
usingSystem;
21+
usingSystem.Collections.Generic;
2122
usingSystem.Diagnostics;
2223
usingSystem.Linq;
2324
usingSystem.Threading.Tasks;
@@ -32,6 +33,7 @@ class RequestLoggingMiddleware
3233
readonlyMessageTemplate_messageTemplate;
3334
readonlyAction<IDiagnosticContext,HttpContext>_enrichDiagnosticContext;
3435
readonlyFunc<HttpContext,double,Exception,LogEventLevel>_getLevel;
36+
readonlyFunc<HttpContext,string,double,int,IEnumerable<LogEventProperty>>_getMessageTemplateProperties;
3537
readonlyILogger_logger;
3638
readonlybool_includeQueryInRequestPath;
3739
staticreadonlyLogEventProperty[]NoProperties=newLogEventProperty[0];
@@ -47,6 +49,7 @@ public RequestLoggingMiddleware(RequestDelegate next, DiagnosticContext diagnost
4749
_messageTemplate=newMessageTemplateParser().Parse(options.MessageTemplate);
4850
_logger=options.Logger?.ForContext<RequestLoggingMiddleware>();
4951
_includeQueryInRequestPath=options.IncludeQueryInRequestPath;
52+
_getMessageTemplateProperties=options.GetMessageTemplateProperties;
5053
}
5154

5255
// ReSharper disable once UnusedMember.Global
@@ -90,13 +93,7 @@ bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector
9093
collectedProperties=NoProperties;
9194

9295
// Last-in (correctly) wins...
93-
varproperties=collectedProperties.Concat(new[]
94-
{
95-
newLogEventProperty("RequestMethod",newScalarValue(httpContext.Request.Method)),
96-
newLogEventProperty("RequestPath",newScalarValue(GetPath(httpContext,_includeQueryInRequestPath))),
97-
newLogEventProperty("StatusCode",newScalarValue(statusCode)),
98-
newLogEventProperty("Elapsed",newScalarValue(elapsedMs))
99-
});
96+
varproperties=collectedProperties.Concat(_getMessageTemplateProperties(httpContext,GetPath(httpContext,_includeQueryInRequestPath),elapsedMs,statusCode));
10097

10198
varevt=newLogEvent(DateTimeOffset.Now,level,ex??collectedException,_messageTemplate,properties);
10299
logger.Write(evt);
@@ -123,7 +120,7 @@ static string GetPath(HttpContext httpContext, bool includeQueryInRequestPath)
123120
{
124121
requestPath=httpContext.Request.Path.ToString();
125122
}
126-
123+
127124
returnrequestPath;
128125
}
129126
}

‎src/Serilog.AspNetCore/AspNetCore/RequestLoggingOptions.cs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
usingMicrosoft.AspNetCore.Http;
1616
usingSerilog.Events;
1717
usingSystem;
18+
usingSystem.Collections.Generic;
1819

1920
// ReSharper disable UnusedAutoPropertyAccessor.Global
2021

@@ -34,6 +35,15 @@ static LogEventLevel DefaultGetLevel(HttpContext ctx, double _, Exception ex) =>
3435
:ctx.Response.StatusCode>499
3536
?LogEventLevel.Error
3637
:LogEventLevel.Information;
38+
39+
IEnumerable<LogEventProperty>DefaultGetMessageTemplateProperties(HttpContexthttpContext,stringrequestPath,doubleelapsedMs,intstatusCode)=>
40+
new[]
41+
{
42+
newLogEventProperty("RequestMethod",newScalarValue(httpContext.Request.Method)),
43+
newLogEventProperty("RequestPath",newScalarValue(requestPath)),
44+
newLogEventProperty("StatusCode",newScalarValue(statusCode)),
45+
newLogEventProperty("Elapsed",newScalarValue(elapsedMs))
46+
};
3747

3848
/// <summary>
3949
/// Gets or sets the message template. The default value is
@@ -74,13 +84,19 @@ static LogEventLevel DefaultGetLevel(HttpContext ctx, double _, Exception ex) =>
7484
/// </summary>
7585
publicboolIncludeQueryInRequestPath{get;set;}
7686

87+
/// <summary>
88+
/// A function to specify the values of the MessageTemplateProperties.
89+
/// </summary>
90+
publicFunc<HttpContext,string,double,int,IEnumerable<LogEventProperty>>GetMessageTemplateProperties{get;set;}
91+
7792
/// <summary>
7893
/// Constructor
7994
/// </summary>
8095
publicRequestLoggingOptions()
8196
{
8297
GetLevel=DefaultGetLevel;
8398
MessageTemplate=DefaultRequestCompletionMessageTemplate;
99+
GetMessageTemplateProperties=DefaultGetMessageTemplateProperties;
84100
}
85101
}
86102
}

‎test/Serilog.AspNetCore.Tests/SerilogWebHostBuilderExtensionsTests.cs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
usingMicrosoft.AspNetCore.Http;
1313
usingSerilog.Filters;
1414
usingSerilog.AspNetCore.Tests.Support;
15+
usingSerilog.Events;
16+
usingSystem.Net.Http;
1517

1618
// Newer frameworks provide IHostBuilder
1719
#pragma warning disableCS0618
@@ -66,6 +68,34 @@ public async Task RequestLoggingMiddlewareShouldEnrich()
6668
Assert.True(completionEvent.Properties.ContainsKey("Elapsed"));
6769
}
6870

71+
[Fact]
72+
publicasyncTaskRequestLoggingMiddlewareShouldEnrichWithCustomisedProperties()
73+
{
74+
var(sink,web)=Setup(options=>
75+
{
76+
options.MessageTemplate="HTTP {RequestMethod} responded {Status} in {ElapsedMilliseconds:0.0000} ms";
77+
options.GetMessageTemplateProperties=(ctx,path,elapsedMs,status)=>
78+
new[]
79+
{
80+
newLogEventProperty("RequestMethod",newScalarValue(ctx.Request.Method)),
81+
newLogEventProperty("Status",newScalarValue(status)),
82+
newLogEventProperty("ElapsedMilliseconds",newScalarValue(elapsedMs))
83+
};
84+
});
85+
86+
awaitweb.CreateClient().GetAsync("/resource");
87+
88+
Assert.NotEmpty(sink.Writes);
89+
90+
varcompletionEvent=sink.Writes.First(logEvent=>Matching.FromSource<RequestLoggingMiddleware>()(logEvent));
91+
92+
Assert.Equal("string",completionEvent.Properties["SomeString"].LiteralValue());
93+
Assert.Equal(200,completionEvent.Properties["Status"].LiteralValue());
94+
Assert.Equal("GET",completionEvent.Properties["RequestMethod"].LiteralValue());
95+
Assert.True(completionEvent.Properties.ContainsKey("ElapsedMilliseconds"));
96+
Assert.False(completionEvent.Properties.ContainsKey("Elapsed"));
97+
}
98+
6999
[Fact]
70100
publicasyncTaskRequestLoggingMiddlewareShouldEnrichWithCollectedExceptionIfNoUnhandledException()
71101
{

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp