Skip to content

Commit

Permalink
Merge pull request #388 from DFE-Digital/feature/add-serilog-api-user…
Browse files Browse the repository at this point in the history
…-enricher

Feature/add serilog api user enricher
  • Loading branch information
paullocknimble authored Oct 5, 2023
2 parents 73f04ad + 7bb75ec commit 56ad544
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 23 deletions.
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>();

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"

Check warning on line 22 in TramsDataApi/appsettings.json

View workflow job for this annotation

GitHub Actions / build-and-test

"password" detected here, make sure this is not a hard-coded credential. (https://rules.sonarsource.com/csharp/RSPEC-2068)
},
"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"
}
}
}

0 comments on commit 56ad544

Please sign in to comment.