Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/add serilog api user enricher #388

Merged
merged 2 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 36 additions & 22 deletions TramsDataApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,39 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using TramsDataApi;
using TramsDataApi.SerilogCustomEnrichers;

namespace TramsDataApi
var builder = WebApplication.CreateBuilder(args);


var startup = new Startup(builder.Configuration);

startup.ConfigureServices(builder.Services);

builder.Host.UseSerilog((context, services, loggerConfiguration) =>
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args)
{
var builder = Host.CreateDefaultBuilder(args);
return builder.ConfigureLogging(c =>
{
c.ClearProviders();
c.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
}
}
var enricher = services.GetRequiredService<ApiUserEnricher>();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the GetRequiredService call it'll throw an exception if the service isn't registered. Is that what we want or do we want some handling of it? I'd guess it probably does constitute a exceptional state, so am happy as is


loggerConfiguration
.WriteTo.ApplicationInsights(services.GetRequiredService<TelemetryConfiguration>(), TelemetryConverter.Traces)
.Enrich.FromLogContext()
.Enrich.With(enricher)
.WriteTo.Console();
});

var app = builder.Build();

var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();

startup.Configure(app, app.Environment, provider);

ILogger<Program> logger = app.Services.GetRequiredService<ILogger<Program>>();

logger.LogInformation("Logger is working...");

app.Run();
57 changes: 57 additions & 0 deletions TramsDataApi/SerilogCustomEnrichers/ApiUserEnricher.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using TramsDataApi.ResponseModels;
using TramsDataApi.UseCases;

namespace TramsDataApi.SerilogCustomEnrichers
{
public class ApiUserEnricher : ILogEventEnricher
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IUseCase<string, ApiUser> _apiKeyService;

public ApiUserEnricher(IHttpContextAccessor httpContextAccessor, IUseCase<string, ApiUser> apiKeyService)
{
_httpContextAccessor = httpContextAccessor;
_apiKeyService = apiKeyService;
}

public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
{
var httpContext = _httpContextAccessor.HttpContext;

if (httpContext is null)
{
return;
}

ApiUser user = null;

if (httpContext.Request.Headers.TryGetValue("ApiKey", out var apiKey))
{
user = _apiKeyService.Execute(apiKey);
}

var httpContextModel = new HttpContextModel
{
Method = httpContext.Request.Method,
User = user?.UserName ?? "Unknow or not applicable"

};

logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty("ApiUser", httpContextModel.User, true));
}
}

public class HttpContextModel
{
public string Method { get; init; }

public string User { get; init; }
}
}
5 changes: 5 additions & 0 deletions TramsDataApi/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ namespace TramsDataApi
using Middleware;
using Swagger;
using UseCases;
using TramsDataApi.SerilogCustomEnrichers;
using TramsDataApi.ResponseModels;

public class Startup
{
Expand Down Expand Up @@ -90,6 +92,9 @@ public void ConfigureServices(IServiceCollection services)
opt.ConnectionString = appInsightsCnnStr;
});
}

services.AddSingleton<IUseCase<string, ApiUser>, ApiKeyService>();
services.AddSingleton<ApiUserEnricher>();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand Down
2 changes: 2 additions & 0 deletions TramsDataApi/TramsDataApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.19" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="TimeZoneConverter" Version="6.1.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
Expand Down
18 changes: 17 additions & 1 deletion TramsDataApi/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,21 @@
"ConnectionStrings": {
"DefaultConnection": "Server=localhost,1433;Database=sip;User Id=sa;TrustServerCertificate=True;Password=Your_password123"
},
"SyncAcademyConversionProjectsSchedule": "0 0/15 * * * *"
"SyncAcademyConversionProjectsSchedule": "0 0/15 * * * *",
"Serilog": {
"Using": [
"Serilog.Sinks.ApplicationInsights"
],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext" ],
"Properties": {
"Application": "Dfe.Academies.Api"
}
}
}