Skip to content

Commit 9b61b21

Browse files
committed
AddHttpLoggingRedaction
1 parent 1a0765e commit 9b61b21

4 files changed

Lines changed: 98 additions & 41 deletions

File tree

src/plugins/SerilogTest/Controllers/LogTestController.cs

Lines changed: 76 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1+
using Microsoft.AspNetCore.HttpLogging;
12
using Microsoft.AspNetCore.Mvc;
23
using Serilog.Context;
4+
using System.Net;
35

46
namespace SerilogTest.Controllers;
57

@@ -10,13 +12,21 @@ public class LogTestController : ControllerBase
1012

1113
#region Constants & Statics
1214

13-
private static readonly string[] Summaries = ["Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"];
15+
private static void InnerMehtod(int? abc)
16+
{
17+
Console.WriteLine(abc);
18+
19+
throw new MyException("the InnerMehtod throw");
20+
}
1421

1522
#endregion
1623

17-
private readonly ILogger<LogTestController> _logger;
24+
private readonly string[] _summaries = ["Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"];
25+
1826
private readonly IHttpContextAccessor _httpContextAccessor;
1927

28+
private readonly ILogger<LogTestController> _logger;
29+
2030
public LogTestController(ILogger<LogTestController> logger, IHttpContextAccessor httpContextAccessor)
2131
{
2232
_logger = logger;
@@ -25,6 +35,42 @@ public LogTestController(ILogger<LogTestController> logger, IHttpContextAccessor
2535

2636
#region Methods
2737

38+
[HttpGet("LogError")]
39+
public IActionResult LogError()
40+
{
41+
_logger.LogError(new MyException("LogError action called"), "this is error message.");
42+
43+
return Ok();
44+
}
45+
46+
[HttpGet("LogErrorThrow")]
47+
public IActionResult LogErrorThrow(int? abc)
48+
{
49+
InnerMehtod(abc);
50+
51+
return Ok();
52+
}
53+
54+
[HttpGet("LoggerScope")]
55+
[HttpLogging(HttpLoggingFields.RequestPropertiesAndHeaders)]
56+
[ProducesResponseType<WeatherForecast>(((int)HttpStatusCode.OK))]
57+
public IActionResult LoggerScope()
58+
{
59+
using (_logger.BeginScope("scope 1"))
60+
{
61+
// ["scope 1"]
62+
_logger.LogInformation("sth. 1");
63+
64+
using (_logger.BeginScope("scope 2"))
65+
{
66+
// ["scope 1", "scope 2"]
67+
_logger.LogInformation("sth. 2");
68+
}
69+
}
70+
71+
return Ok();
72+
}
73+
2874
[HttpGet("LogWarning")]
2975
public IEnumerable<WeatherForecast> LogWarning()
3076
{
@@ -41,7 +87,7 @@ public IEnumerable<WeatherForecast> LogWarning()
4187
DateTime = dateTime,
4288
DateTimeOffset = DateTimeOffset.UtcNow,
4389
TemperatureC = Random.Shared.Next(-20, 55),
44-
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
90+
Summary = _summaries[Random.Shared.Next(_summaries.Length)]
4591
};
4692
})
4793
.ToArray();
@@ -51,38 +97,44 @@ public IEnumerable<WeatherForecast> LogWarning()
5197
return arr;
5298
}
5399

54-
[HttpGet("LogError")]
55-
public IActionResult LogError()
56-
{
57-
_logger.LogError(new MyException("LogError action called"), "this is error message.");
58-
59-
return Ok();
60-
}
61-
62-
[HttpGet("LogErrorThrow")]
63-
public IActionResult LogErrorThrow(int? abc)
100+
[HttpGet("OnlyLogRequest")]
101+
[HttpLogging(HttpLoggingFields.RequestPropertiesAndHeaders)]
102+
[ProducesResponseType<WeatherForecast>(((int)HttpStatusCode.OK))]
103+
public IActionResult OnlyLogRequest()
64104
{
65-
InnerMehtod(abc);
66-
67-
return Ok();
68-
}
69-
70-
private static void InnerMehtod(int? abc)
71-
{
72-
Console.WriteLine(abc);
73-
74-
throw new MyException("the InnerMehtod throw");
105+
var dateTime = DateTime.Now.AddDays(1);
106+
107+
return Ok(
108+
new WeatherForecast
109+
{
110+
Date = DateOnly.FromDateTime(dateTime),
111+
DateTime = dateTime,
112+
DateTimeOffset = DateTimeOffset.UtcNow,
113+
TemperatureC = Random.Shared.Next(-20, 55),
114+
Summary = _summaries[Random.Shared.Next(_summaries.Length)]
115+
});
75116
}
76117

77118
[HttpGet("UseLogContext")]
119+
[ProducesResponseType<WeatherForecast>(((int)HttpStatusCode.OK))]
78120
public IActionResult UseLogContext()
79121
{
80122
using var _ = LogContext.PushProperty("TenantId", Guid.NewGuid());
81123
using var __ = LogContext.PushProperty("UserId", 1);
82124

83125
_logger.LogInformation("method starting: {Method}", nameof(UseLogContext));
84126

85-
return Ok();
127+
var dateTime = DateTime.Now.AddDays(1);
128+
129+
return Ok(
130+
new WeatherForecast
131+
{
132+
Date = DateOnly.FromDateTime(dateTime),
133+
DateTime = dateTime,
134+
DateTimeOffset = DateTimeOffset.UtcNow,
135+
TemperatureC = Random.Shared.Next(-20, 55),
136+
Summary = _summaries[Random.Shared.Next(_summaries.Length)]
137+
});
86138
}
87139

88140
#endregion

src/plugins/SerilogTest/Program.cs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using Microsoft.AspNetCore.HttpLogging;
1+
using Microsoft.AspNetCore.HttpLogging;
22
using Serilog;
33
using Serilog.Core;
44
using Serilog.Exceptions;
@@ -7,7 +7,7 @@
77

88
namespace SerilogTest;
99

10-
internal class Program
10+
internal sealed class Program
1111
{
1212

1313
#region Constants & Statics
@@ -53,12 +53,21 @@ private static async Task Main(string[] args)
5353
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
5454
_ = services.AddOpenApi();
5555

56-
_ = services
57-
.AddHttpLogging(
58-
(options) =>
59-
{
60-
options.LoggingFields = HttpLoggingFields.All;
61-
});
56+
_ = services.AddHttpLogging(
57+
(options) =>
58+
{
59+
options.LoggingFields = HttpLoggingFields.All;
60+
options.CombineLogs = true;
61+
});
62+
63+
_ = services.AddRedaction();
64+
_ = services.AddHttpLoggingRedaction(
65+
options =>
66+
{
67+
// Add the paths that should be filtered, with a leading '/'.
68+
_ = options.ExcludePathStartsWith.Add("/openapi");
69+
options.IncludeUnmatchedRoutes = true;
70+
});
6271

6372
_ = services.AddHealthChecks();
6473

@@ -126,7 +135,7 @@ static LoggerConfiguration ConfigureLogger(LoggerConfiguration configuration)
126135

127136
#endregion
128137

129-
protected Program()
138+
private Program()
130139
{
131140
}
132141
}

src/plugins/SerilogTest/SerilogTest.csproj

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77
</PropertyGroup>
88

99
<ItemGroup>
10+
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.Middleware" Version="9.4.0" />
1011
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
12+
<PackageReference Include="Microsoft.Extensions.Compliance.Redaction" Version="9.4.0" />
1113
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
1214
<PackageReference Include="Serilog.Enrichers.ClientInfo" Version="2.1.2" />
1315
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.0.1" />

src/plugins/SerilogTest/appsettings.json

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"Override": {
66
"Microsoft.AspNetCore.Mvc": "Warning",
77
"Microsoft.AspNetCore.Routing": "Warning",
8-
"Microsoft.AspNetCore.Hosting": "Information"
8+
"Microsoft.AspNetCore.Hosting": "Warning"
99
}
1010
},
1111
"Enrich": [
@@ -18,12 +18,6 @@
1818
"WithThreadName",
1919
"WithClientIp",
2020
"WithCorrelationId"
21-
// {
22-
// "Name": "WithRequestHeader",
23-
// "Args": {
24-
// "headerName": "User-Agent"
25-
// }
26-
// }
2721
],
2822
"WriteTo": [
2923
{
@@ -33,7 +27,7 @@
3327
{
3428
"Name": "Console",
3529
"Args": {
36-
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} {NewLine}{Message:lj}{NewLine}{Properties:lj}{NewLine}{Exception}{NewLine}"
30+
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} {Scope} {NewLine}{Message:lj}{NewLine}{Properties:j}{NewLine}{Exception}{NewLine}"
3731
}
3832
},
3933
{

0 commit comments

Comments
 (0)