Skip to content

Commit

Permalink
Imroved Logging - added CorrelationId to logs
Browse files Browse the repository at this point in the history
  • Loading branch information
crni99 committed Sep 11, 2024
1 parent b4c1a80 commit 500ad42
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 54 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.11" />
<PackageReference Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.AspNetCore.Http;
using Serilog.Context;

namespace AirportAutomation.Infrastructure.Middlewares
{
public class RequestLogContextMiddleware
{
private readonly RequestDelegate _next;

public RequestLogContextMiddleware(RequestDelegate next)
{
_next = next;
}

public Task InvokeAsync(HttpContext context)
{
using (LogContext.PushProperty("CorrelationId", context.TraceIdentifier))
{
return _next(context);
}
}

}
}
20 changes: 5 additions & 15 deletions AirportAutomation/AirportAutomationWeb/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,12 @@
using AirportAutomation.Infrastructure.Middlewares;
using AirportAutomation.Web.Binders;
using Serilog;
using Serilog.Events;

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Is(LogEventLevel.Information)
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(le => le.Level >= LogEventLevel.Information)
.WriteTo.Console()
)
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(le => le.Level >= LogEventLevel.Warning)
.WriteTo.File("Logs/AirportAutomationAPI.txt", rollingInterval: RollingInterval.Day)
)
.CreateLogger();

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog();
builder.Host.UseSerilog((context, loggerConfig) =>
loggerConfig.ReadFrom.Configuration(context.Configuration));

builder.Services.AddCors(options =>
{
options.AddPolicy("_AllowSpecificMethods", builder =>
Expand Down Expand Up @@ -50,6 +38,8 @@
}

app.UseHttpsRedirection();
app.UseMiddleware<RequestLogContextMiddleware>();
app.UseSerilogRequestLogging();
app.UseStaticFiles();
app.UseCors("_AllowSpecificMethods");
app.UseRouting();
Expand Down
46 changes: 38 additions & 8 deletions AirportAutomation/AirportAutomationWeb/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,42 @@
{
"Logging": {
"LogLevel": {
"Default": "Error",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Information",
"Microsoft.EntityFrameworkCore": "Error",
"AirportAutomationApi": "Error"
}
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {CorrelationId} {Message}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "Logs/AirportAutomationAPI-.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {CorrelationId} {Message}{NewLine}{Exception}"
}
}
],
"Filter": [
{
"Name": "ExpressionFilter",
"Args": {
"expression": "Level >= Information"
}
},
{
"Name": "ExpressionFilter",
"Args": {
"expression": "Level >= Warning"
}
}
]
},
"AllowedHosts": "*",
"ApiSettings": {
Expand Down
20 changes: 5 additions & 15 deletions AirportAutomation/AirportАutomationApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,15 @@
using Microsoft.OpenApi.Models;
using QuestPDF.Infrastructure;
using Serilog;
using Serilog.Events;
using System.Text;

Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Is(LogEventLevel.Information)
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(le => le.Level >= LogEventLevel.Information)
.WriteTo.Console()
)
.WriteTo.Logger(lc => lc
.Filter.ByIncludingOnly(le => le.Level >= LogEventLevel.Warning)
.WriteTo.File("Logs/AirportAutomationAPI.txt", rollingInterval: RollingInterval.Day)
)
.CreateLogger();

QuestPDF.Settings.License = LicenseType.Community;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((context, loggerConfig) =>
loggerConfig.ReadFrom.Configuration(context.Configuration));

builder.Services.AddCors(options =>
{
options.AddPolicy("_AllowAll", builder =>
Expand All @@ -47,7 +36,6 @@
options => options.UseDateOnlyTimeOnlyStringConverters())
.AddJsonOptions(options => options.UseDateOnlyTimeOnlyStringConverters())
.AddNewtonsoftJson();
builder.Host.UseSerilog();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(setupAction =>
{
Expand Down Expand Up @@ -198,6 +186,8 @@
}

app.UseHttpsRedirection();
app.UseMiddleware<RequestLogContextMiddleware>();
app.UseSerilogRequestLogging();
app.MapHealthChecks("/api/v{version:apiVersion}/HealthCheck", new()
{
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
Expand Down
62 changes: 46 additions & 16 deletions AirportAutomation/AirportАutomationApi/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,23 +1,53 @@
{
"Logging": {
"LogLevel": {
"Default": "Error",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Information",
"Microsoft.EntityFrameworkCore": "Error",
"AirportAutomationApi": "Error"
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning"
}
},
"AllowedHosts": "*",
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {CorrelationId} {Message}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "Logs/AirportAutomationAPI-.txt",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss} [{Level}] {CorrelationId} {Message}{NewLine}{Exception}"
}
}
],
"Filter": [
{
"Name": "ExpressionFilter",
"Args": {
"expression": "Level >= Information"
}
},
{
"Name": "ExpressionFilter",
"Args": {
"expression": "Level >= Warning"
}
}
]
},
"AllowedHosts": "*",
"ConnectionStrings": {
"Default": "Data Source=DESKTOP-JENEFBJ\\SQLEXPRESS;Initial Catalog=AirportАutomation;Integrated Security=True;TrustServerCertificate=True;"
},
"PageSettings": {
"maxPageSize": 10
},
"Authentication": {
"SecretForKey": "This is a sample secret key - please don't use in production environment.",
"Issuer": "https://localhost:7107",
"Audience": "https://localhost:7107"
}
"PageSettings": {
"maxPageSize": 10
},
"Authentication": {
"SecretForKey": "This is a sample secret key - please don't use in production environment.",
"Issuer": "https://localhost:7107",
"Audience": "https://localhost:7107"
}
}

0 comments on commit 500ad42

Please sign in to comment.