Merge pull request #28 from carltibule/feature/SwitchToStructuredLogging

Added structured logging to file and Grafana Loki
This commit is contained in:
Carl Tibule
2023-03-27 21:41:06 -05:00
committed by GitHub
4 changed files with 73 additions and 5 deletions

View File

@ -0,0 +1,26 @@
using Serilog.Context;
using YABA.Common.Extensions;
namespace YABA.API.Middlewares
{
public class AddCustomLoggingPropertiesMiddleware
{
private readonly RequestDelegate _next;
public AddCustomLoggingPropertiesMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
if(httpContext.Request.Path.HasValue && httpContext.Request.Path.Value.Contains("/api"))
{
LogContext.PushProperty("UserId", httpContext.User.Identity.IsAuthenticated ? httpContext.User.Identity.GetUserId() : "Anonymous");
LogContext.PushProperty("RemoteIpAddress", httpContext.Connection.RemoteIpAddress.MapToIPv4());
}
await _next(httpContext);
}
}
}

View File

@ -13,6 +13,7 @@ using YABA.Data.Configuration;
using YABA.Data.Context;
using YABA.Service.Configuration;
using Serilog;
using Microsoft.AspNetCore.HttpOverrides;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
@ -49,6 +50,7 @@ builder.Services.AddHttpContextAccessor();
builder.Services.AddServiceProjectDependencyInjectionConfiguration(configuration);
builder.Services.AddDataProjectDependencyInjectionConfiguration(configuration);
builder.Services.AddControllers().AddNewtonsoftJson();
builder.Services.AddHealthChecks();
// Add AutoMapper profiles
var mapperConfiguration = new MapperConfiguration(mapperConfiguration =>
@ -78,8 +80,14 @@ builder.Services.AddSwaggerGen(
}
);
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
// Add Serilog
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).Enrich.FromLogContext().CreateLogger();
builder.Host.UseSerilog();
var app = builder.Build();
@ -100,6 +108,7 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
app.UseForwardedHeaders();
app.UseAuthentication();
app.UseAuthorization();
@ -107,6 +116,7 @@ app.MapControllers();
// Add custom middlewares
app.UseMiddleware<AddCustomClaimsMiddleware>();
app.UseMiddleware<AddCustomLoggingPropertiesMiddleware>();
app.UseCors(x => x
.AllowAnyOrigin()
@ -115,5 +125,6 @@ app.UseCors(x => x
var webClientUrl = configuration.GetSection("WebClient").GetValue<string>("Url");
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins(webClientUrl));
app.MapHealthChecks("/Pulse");
app.Run();

View File

@ -11,6 +11,7 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.13" />
<PackageReference Include="Microsoft.AspNetCore.HttpOverrides" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.14" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.14">
@ -20,8 +21,12 @@
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.15.1" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0" />
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="8.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.5.0" />
@ -33,4 +38,8 @@
<ProjectReference Include="..\YABA.Service\YABA.Service.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Logs\" />
</ItemGroup>
</Project>

View File

@ -7,16 +7,38 @@
}
},
"Serilog": {
"MinimumLevel": "Information",
"MinimumLevel": "Information",
"Using": [
"Serilog.Sinks.Grafana.Loki"
],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log-.txt",
"rollingInterval": "Day"
"path": "Logs/log.json",
"rollingInterval": "Day",
"formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog"
}
},
{
"Name": "GrafanaLoki",
"Args": {
"uri": "https://loki.iwanaga.moe",
"labels": [
{
"key": "job",
"value": "YABA.API"
},
{
"key": "environment",
"value": "localhost"
}
],
"propertiesAsLabels": [ "job", "environment" ]
}
}
]
],
"Enrich": ["FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId"]
},
"WebClient": {
"Url": "https://localhost:3000"