Skip to content

Commit 5f8f59f

Browse files
committed
Update
1 parent 7ce52b1 commit 5f8f59f

6 files changed

Lines changed: 126 additions & 110 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
3+
namespace SerilogTest.Controllers;
4+
5+
[ApiController]
6+
[Route("[controller]")]
7+
public class LogTestController : ControllerBase
8+
{
9+
10+
#region Constants & Statics
11+
12+
private static readonly string[] Summaries = ["Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"];
13+
14+
#endregion
15+
16+
private readonly ILogger<LogTestController> _logger;
17+
18+
public LogTestController(ILogger<LogTestController> logger)
19+
{
20+
_logger = logger;
21+
}
22+
23+
#region Methods
24+
25+
[HttpGet("LogWarning")]
26+
public IEnumerable<WeatherForecast> LogWarning()
27+
{
28+
_logger.LogInformation("LogWarning calling");
29+
30+
var arr = Enumerable.Range(1, 5)
31+
.Select(
32+
index =>
33+
new WeatherForecast
34+
{
35+
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
36+
TemperatureC = Random.Shared.Next(-20, 55),
37+
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
38+
})
39+
.ToArray();
40+
41+
_logger.LogWarning("result is {@Arr}", arr);
42+
43+
return arr;
44+
}
45+
46+
[HttpGet("LogError")]
47+
public IActionResult LogError()
48+
{
49+
_logger.LogError(new MyException("LogError action called"), "this is error message.");
50+
51+
return Ok();
52+
}
53+
54+
[HttpGet("LogErrorThrow")]
55+
public IActionResult LogErrorThrow(int? abc)
56+
{
57+
InnerMehtod(abc);
58+
59+
return Ok();
60+
}
61+
62+
private static void InnerMehtod(int? abc)
63+
{
64+
Console.WriteLine(abc);
65+
66+
throw new MyException("the InnerMehtod throw");
67+
}
68+
69+
#endregion
70+
71+
}

src/plugins/SerilogTest/Controllers/WeatherForecastController.cs

Lines changed: 0 additions & 51 deletions
This file was deleted.

src/plugins/SerilogTest/Program.cs

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
using Serilog;
2+
using Serilog.Core;
23
using Serilog.Exceptions;
34
using Serilog.Exceptions.Core;
45
using Serilog.Exceptions.EntityFrameworkCore.Destructurers;
56

67
namespace SerilogTest;
78

8-
internal static class Program
9+
internal class Program
910
{
1011

1112
#region Constants & Statics
@@ -20,14 +21,10 @@ private static async Task Main(string[] args)
2021
true)
2122
.Build();
2223

23-
Log.Logger = new LoggerConfiguration()
24+
var loggerConfiguration = new LoggerConfiguration()
2425
.ReadFrom
25-
.Configuration(configuration) // BUG: invalid
26-
.Enrich
27-
.WithExceptionDetails(
28-
new DestructuringOptionsBuilder().WithDefaultDestructurers()
29-
.WithDestructurers([new DbUpdateExceptionDestructurer()]))
30-
.CreateBootstrapLogger();
26+
.Configuration(configuration);
27+
Log.Logger = ConfigureLogger(loggerConfiguration).CreateBootstrapLogger();
3128

3229
try
3330
{
@@ -46,6 +43,7 @@ private static async Task Main(string[] args)
4643
{
4744
_ = options.ReadFrom.Configuration(builderContext.Configuration).ReadFrom
4845
.Services(serviceProvider);
46+
_ = ConfigureLogger(options);
4947
});
5048

5149
_ = builder.Services.AddControllers();
@@ -65,16 +63,16 @@ private static async Task Main(string[] args)
6563
_ = app.UseHsts();
6664
}
6765

68-
_ = app.UseSerilogRequestLogging(
69-
(options) =>
70-
{
71-
// Attach additional properties to the request completion event
72-
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
73-
{
74-
diagnosticContext.Set("RequestHost", httpContext.Request.Host);
75-
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
76-
};
77-
});
66+
//_ = app.UseSerilogRequestLogging(
67+
// (options) =>
68+
// {
69+
// // Attach additional properties to the request completion event
70+
// options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
71+
// {
72+
// diagnosticContext.Set("RequestHost", httpContext.Request.Host);
73+
// diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
74+
// };
75+
// });
7876

7977
_ = app.UseHttpsRedirection();
8078

@@ -94,8 +92,22 @@ private static async Task Main(string[] args)
9492
{
9593
await Log.CloseAndFlushAsync();
9694
}
95+
96+
static LoggerConfiguration ConfigureLogger(LoggerConfiguration configuration)
97+
{
98+
return configuration.Enrich
99+
.WithProperty(Constants.SourceContextPropertyName, typeof(Program).FullName, false)
100+
.Enrich
101+
.WithExceptionDetails(
102+
new DestructuringOptionsBuilder().WithDefaultDestructurers()
103+
//.WithRootName("x")
104+
.WithDestructurers([new DbUpdateExceptionDestructurer()]));
105+
}
97106
}
98107

99108
#endregion
100109

110+
protected Program()
111+
{
112+
}
101113
}
Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
1-
@SerilogTest_HostAddress = http://localhost:5267
1+
@SerilogTest_HostAddress = https://localhost:7119
22

3-
GET {{SerilogTest_HostAddress}}/weatherforecast/
3+
GET {{SerilogTest_HostAddress}}/LogTest/LogWarning/
4+
Accept: application/json
5+
6+
###
7+
8+
GET {{SerilogTest_HostAddress}}/LogTest/LogError/
9+
Accept: application/json
10+
11+
###
12+
13+
GET {{SerilogTest_HostAddress}}/LogTest/LogErrorThrow/
414
Accept: application/json
515

616
###
Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,5 @@
11
{
22
"Serilog": {
3-
"MinimumLevel": {
4-
"Default": "Debug",
5-
"Override": {
6-
"Microsoft": "Debug",
7-
"System": "Information"
8-
}
9-
},
10-
"WriteTo": [
11-
{
12-
"Name": "Console",
13-
"Args": {
14-
"outputTemplate": "{Timestamp:HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
15-
}
16-
}
17-
]
18-
},
19-
"Logging": {
20-
"LogLevel": {
21-
"Default": "Information",
22-
"Microsoft.AspNetCore": "Warning"
23-
}
3+
"MinimumLevel": {}
244
}
255
}
Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
{
22
"Serilog": {
33
"MinimumLevel": {
4-
"Default": "Debug",
4+
"Default": "Information",
55
"Override": {
6-
"Microsoft": "Information",
7-
"System": "Warning"
6+
"Microsoft.AspNetCore.Mvc": "Warning",
7+
"Microsoft.AspNetCore.Routing": "Warning",
8+
"Microsoft.AspNetCore.Hosting": "Information"
89
}
910
},
1011
"Enrich": [
@@ -22,9 +23,7 @@
2223
"Args": {
2324
"headerName": "User-Agent"
2425
}
25-
},
26-
"WithExceptionDetails",
27-
"WithProperty"
26+
}
2827
],
2928
"WriteTo": [
3029
{
@@ -34,15 +33,17 @@
3433
{
3534
"Name": "Console",
3635
"Args": {
37-
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} {Message:lj}{NewLine}{Properties:lj}{NewLine}{Exception}"
36+
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext} {NewLine}{Message:lj}{NewLine}{Properties:lj}{NewLine}"
3837
}
3938
},
4039
{
4140
"Name": "File",
4241
"Args": {
4342
"path": "logs/log-.txt",
4443
"rollingInterval": "Minute",
45-
"retainedFileCountLimit": 10,
44+
"rollOnFileSizeLimit": true,
45+
"fileSizeLimitBytes": 104857600,
46+
"retainedFileCountLimit": 14,
4647
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
4748
}
4849
},
@@ -52,7 +53,9 @@
5253
"restrictedToMinimumLevel": "Error",
5354
"path": "logs/log-error-.txt",
5455
"rollingInterval": "Minute",
55-
"retainedFileCountLimit": 10,
56+
"rollOnFileSizeLimit": true,
57+
"fileSizeLimitBytes": 104857600,
58+
"retainedFileCountLimit": 14,
5659
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
5760
}
5861
}
@@ -61,14 +64,5 @@
6164
}
6265
]
6366
},
64-
"Logging": {
65-
"LogLevel": {
66-
"Default": "Information"
67-
// "Microsoft.AspNetCore.Mvc": "Warning",
68-
// "Microsoft.AspNetCore.Routing": "Warning",
69-
// "Microsoft.AspNetCore.Hosting": "Warning"
70-
// "Microsoft.AspNetCore": "Warning"
71-
}
72-
},
7367
"AllowedHosts": "*"
7468
}

0 commit comments

Comments
 (0)