Skip to content

Commit de9b027

Browse files
committed
Integrate Serilog for Enhanced Logging
Added Serilog packages to `PdfSmith.csproj` for structured logging. Integrated Serilog in `Program.cs` to log HTTP requests and configured it using `appsettings.Development.json` and `appsettings.json`. Introduced `HttpContextLogEventEnricher` to enrich logs with user information. Updated logging to write to console and SQL Server, providing detailed control over log output and filtering. Closes #6
1 parent e43b4bf commit de9b027

File tree

5 files changed

+115
-11
lines changed

5 files changed

+115
-11
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
using Serilog.Core;
2+
using Serilog.Events;
3+
4+
namespace PdfSmith.Logging;
5+
6+
public class HttpContextEnricher(IHttpContextAccessor httpContextAccessor) : ILogEventEnricher
7+
{
8+
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
9+
{
10+
var httpContext = httpContextAccessor.HttpContext;
11+
12+
if (httpContext is null)
13+
{
14+
return;
15+
}
16+
17+
logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("UserName", httpContext.User?.Identity?.Name));
18+
}
19+
}

src/PdfSmith/PdfSmith.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore" Version="9.0.9" />
1919
<PackageReference Include="MinimalHelpers.FluentValidation" Version="1.1.4" />
2020
<PackageReference Include="OperationResultTools.AspNetCore.Http" Version="1.0.30" />
21+
<PackageReference Include="Serilog.AspNetCore" Version="9.0.0" />
22+
<PackageReference Include="Serilog.Expressions" Version="5.0.0" />
23+
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="8.2.2" />
2124
<PackageReference Include="SimpleAuthenticationTools" Version="3.0.15" />
2225
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="9.0.6" />
2326
<PackageReference Include="TinyHelpers.AspNetCore" Version="4.1.6" />

src/PdfSmith/Program.cs

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,16 +25,25 @@
2525
using PdfSmith.BusinessLayer.Validations;
2626
using PdfSmith.DataAccessLayer;
2727
using PdfSmith.HealthChecks;
28+
using PdfSmith.Logging;
2829
using PdfSmith.Shared.Models;
30+
using Serilog;
31+
using Serilog.Core;
2932
using SimpleAuthentication;
3033
using SimpleAuthentication.ApiKey;
3134
using TinyHelpers.AspNetCore.Extensions;
3235
using TinyHelpers.AspNetCore.OpenApi;
3336

3437
var builder = WebApplication.CreateBuilder(args);
38+
builder.Host.UseSerilog((hostingContext, services, loggerConfiguration) =>
39+
{
40+
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);
41+
loggerConfiguration.ReadFrom.Services(services);
42+
});
3543

3644
// Add services to the container.
3745
builder.Services.AddHttpContextAccessor();
46+
builder.Services.AddSingleton<ILogEventEnricher, HttpContextEnricher>();
3847

3948
builder.Services.AddSingleton(TimeProvider.System);
4049
builder.Services.AddSingleton<RequestTimeProvider>();
@@ -167,6 +176,12 @@
167176
app.UseRequestLocalization();
168177

169178
app.UseAuthentication();
179+
180+
app.UseSerilogRequestLogging(options =>
181+
{
182+
options.IncludeQueryInRequestPath = true;
183+
});
184+
170185
app.UseAuthorization();
171186

172187
app.UseRateLimiter();
@@ -252,4 +267,5 @@ static Func<HttpContext, HealthReport, Task> HealthChecksResponseWriter()
252267

253268
context.Response.ContentType = MediaTypeNames.Application.Json;
254269
await context.Response.WriteAsync(result);
255-
};
270+
};
271+
Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
11
{
22
"ConnectionStrings": {
3-
"SqlConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MinimalDB;Integrated Security=true"
3+
"SqlConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MinimalDB;Integrated Security=true",
4+
"LogsConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=MinimalDB;Integrated Security=true"
45
},
56
"AppSettings": {
67
"AdministratorUserName": "[email protected]",
78
"AdministratorApiKey": "KNIkRRngxoOyo2e1egkrz4wUi3pfyaD4g0q3uZTp6jaRMtThx9"
89
},
9-
"Logging": {
10-
"LogLevel": {
11-
"Default": "Information",
12-
"Microsoft.AspNetCore": "Warning"
10+
"Serilog": {
11+
"MinimumLevel": {
12+
"Override": {
13+
"Microsoft.AspNetCore": "Warning",
14+
"Microsoft.EntityFrameworkCore": "Information",
15+
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
16+
}
1317
}
1418
}
1519
}

src/PdfSmith/appsettings.json

Lines changed: 67 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
{
22
"ConnectionStrings": {
3-
"SqlConnection": ""
3+
"SqlConnection": "",
4+
"LogsConnection": ""
45
},
56
"Authentication": {
67
"ApiKey": {
@@ -11,11 +12,72 @@
1112
"AdministratorUserName": null,
1213
"AdministratorApiKey": null
1314
},
14-
"Logging": {
15-
"LogLevel": {
15+
"Serilog": {
16+
"Using": [ "Serilog.Sinks.MSSqlServer", "Serilog.Expressions" ],
17+
"MinimumLevel": {
1618
"Default": "Information",
17-
"Microsoft.AspNetCore": "Warning"
18-
}
19+
"Override": {
20+
"Microsoft": "Warning",
21+
"Microsoft.AspNetCore.Identity": "Error",
22+
"Microsoft.EntityFrameworkCore": "Error",
23+
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
24+
"System": "Warning"
25+
}
26+
},
27+
"WriteTo": [
28+
{
29+
"Name": "Debug"
30+
},
31+
{
32+
"Name": "Console",
33+
"Args": {
34+
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
35+
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} <{SourceContext}>{NewLine}{Exception}"
36+
}
37+
},
38+
{
39+
"Name": "MSSqlServer",
40+
"Args": {
41+
"connectionString": "LogsConnection",
42+
"sinkOptionsSection": {
43+
"tableName": "Logs",
44+
"autoCreateSqlTable": true
45+
},
46+
"restrictedToMinimumLevel": "Information",
47+
"columnOptionsSection": {
48+
"addStandardColumns": [ "LogEvent", "TraceId", "SpanId" ],
49+
"removeStandardColumns": [ "MessageTemplate", "Properties" ],
50+
"additionalColumns": [
51+
{
52+
"ColumnName": "UserName",
53+
"PropertyName": "UserName",
54+
"DataType": "nvarchar",
55+
"DataLength": 255,
56+
"AllowNull": true
57+
}
58+
],
59+
"id": { "dataType": "bigint" },
60+
"timeStamp": {
61+
"columnName": "Timestamp",
62+
"convertToUtc": true
63+
},
64+
"logEvent": {
65+
"excludeAdditionalProperties": false,
66+
"excludeStandardColumns": false
67+
}
68+
}
69+
}
70+
}
71+
],
72+
"Filter": [
73+
{
74+
"Name": "ByExcluding",
75+
"Args": {
76+
"expression": "RequestMethod = 'OPTIONS' OR RequestPath LIKE '/openapi/%'"
77+
}
78+
}
79+
],
80+
"Enrich": [ "FromLogContext" ]
1981
},
2082
"AllowedHosts": "*",
2183
"https_ports": "443"

0 commit comments

Comments
 (0)