Skip to content

Commit

Permalink
Add serilog logging
Browse files Browse the repository at this point in the history
  • Loading branch information
harryy94 committed Jan 24, 2025
1 parent 9b25503 commit cf90756
Show file tree
Hide file tree
Showing 8 changed files with 684 additions and 130 deletions.
4 changes: 2 additions & 2 deletions src/infrastructure/terraform/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ resource "azurerm_resource_group" "core-rg" {
}

resource "azurerm_log_analytics_workspace" "log-analytics-workspace" {
name = "${var.environment_prefix}-log-analytics-workspace"
name = "${local.service_prefix}-log-analytics-workspace"
location = azurerm_resource_group.core-rg.location
resource_group_name = azurerm_resource_group.core-rg.name
retention_in_days = 180
tags = local.common_tags
}

resource "azurerm_application_insights" "application-insights" {
name = "${var.environment_prefix}-app-insights"
name = "${local.service_prefix}-app-insights"
location = azurerm_resource_group.core-rg.location
resource_group_name = azurerm_resource_group.core-rg.name
application_type = "web"
Expand Down
4 changes: 4 additions & 0 deletions src/infrastructure/terraform/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,23 @@ variable "environment_prefix" {
variable "github_principal" {
description = "Github principal"
type = string
sensitive = true
}

variable "contentful_delivery_api_key" {
description = "Contentful Delivery API Key"
type = string
sensitive = true
}

variable "contentful_preview_api_key" {
description = "Contentful Preview API Key"
type = string
sensitive = true
}

variable "contentful_space_id" {
description = "Contentful Space ID"
type = string
sensitive = true
}
1 change: 1 addition & 0 deletions src/infrastructure/terraform/web.tf
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ resource "azurerm_linux_web_app" "web-app-service" {
name = "${local.service_prefix}-web-app-service"
resource_group_name = azurerm_resource_group.web-rg.name
key_vault_reference_identity_id = azurerm_user_assigned_identity.web-app-identity.id
https_only = true

site_config {
always_on = true
Expand Down
4 changes: 4 additions & 0 deletions src/web/CareLeavers.Web/CareLeavers.Web.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.2.0" />
<PackageReference Include="contentful.aspnetcore" Version="8.3.0" />
<PackageReference Include="GovUk.Frontend.AspNetCore" Version="2.8.0" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
29 changes: 29 additions & 0 deletions src/web/CareLeavers.Web/LoggingConfigurationExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Microsoft.ApplicationInsights.Extensibility;
using Serilog;
using Serilog.Events;

namespace CareLeavers.Web;

public static class LoggingConfigurationExtensions
{
public static LoggerConfiguration ConfigureLogging(
this LoggerConfiguration loggerConfig,
string? appInsightsConnectionString)
{
var config = loggerConfig
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.WriteTo.Console()
.Enrich.FromLogContext();

if (!string.IsNullOrEmpty(appInsightsConnectionString))
{
config = config.WriteTo.ApplicationInsights(new TelemetryConfiguration
{
ConnectionString = appInsightsConnectionString
}, TelemetryConverter.Traces);
}

return config;
}
}
125 changes: 77 additions & 48 deletions src/web/CareLeavers.Web/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Azure.Monitor.OpenTelemetry.AspNetCore;
using CareLeavers.Web;
using CareLeavers.Web.Caching;
using CareLeavers.Web.Configuration;
Expand All @@ -7,75 +8,103 @@
using Contentful.Core.Models;
using GovUk.Frontend.AspNetCore;
using Microsoft.Extensions.Caching.Distributed;
using Serilog;

var builder = WebApplication.CreateBuilder(args);
Log.Logger = new LoggerConfiguration()
.ConfigureLogging(Environment.GetEnvironmentVariable("ApplicationInsights__ConnectionString"))
.CreateBootstrapLogger();

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddGovUkFrontend();
try
{
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();
builder.Services.AddGovUkFrontend();

builder.Services.AddSerilog((_, lc) => lc
.ConfigureLogging(builder.Configuration["ApplicationInsights:ConnectionString"]));

var connString = builder.Configuration.GetValue<string>("ApplicationInsights:ConnectionString");

if (!string.IsNullOrEmpty(connString))
{
builder.Services.AddOpenTelemetry()
.UseAzureMonitor(x => x.ConnectionString = connString);
}

builder.Services.AddContentful(builder.Configuration);
builder.Services.AddContentful(builder.Configuration);

builder.Services.AddTransient<HtmlRenderer>((c) => {
var renderer = new HtmlRenderer(new HtmlRendererOptions
builder.Services.AddTransient<HtmlRenderer>((c) =>
{
ListItemOptions = new ListItemContentRendererOptions
var renderer = new HtmlRenderer(new HtmlRendererOptions
{
OmitParagraphTagsInsideListItems = true
}
ListItemOptions = new ListItemContentRendererOptions
{
OmitParagraphTagsInsideListItems = true
}
});

// Add custom GDS renderer
renderer.AddRenderer(new GDSParagraphRenderer(renderer.Renderers));
renderer.AddRenderer(new GDSHeaderRenderer(renderer.Renderers));

return renderer;
});

// Add custom GDS renderer
renderer.AddRenderer(new GDSParagraphRenderer(renderer.Renderers));
renderer.AddRenderer(new GDSHeaderRenderer(renderer.Renderers));

return renderer;
});

builder.Services.Configure<CachingOptions>(
builder.Configuration.GetSection(CachingOptions.Name)
);
builder.Services.Configure<CachingOptions>(
builder.Configuration.GetSection(CachingOptions.Name)
);

builder.Services.AddOptions<CachingOptions>().BindConfiguration("Caching");
var cachingOptions = builder.Configuration.GetSection("Caching").Get<CachingOptions>();
builder.Services.AddOptions<CachingOptions>().BindConfiguration("Caching");
var cachingOptions = builder.Configuration.GetSection("Caching").Get<CachingOptions>();

if (cachingOptions?.Enabled == true)
{
builder.Services.AddDistributedMemoryCache();
}
else
{
builder.Services.AddSingleton<IDistributedCache, CacheDisabledDistributedCache>();
}
if (cachingOptions?.Enabled == true)
{
builder.Services.AddDistributedMemoryCache();
}
else
{
builder.Services.AddSingleton<IDistributedCache, CacheDisabledDistributedCache>();
}

var app = builder.Build();
var app = builder.Build();

var contentfulClient = app.Services.GetRequiredService<IContentfulClient>();
var contentfulClient = app.Services.GetRequiredService<IContentfulClient>();

Constants.Serializer = contentfulClient.Serializer;
Constants.SerializerSettings = contentfulClient.SerializerSettings;
Constants.Serializer = contentfulClient.Serializer;
Constants.SerializerSettings = contentfulClient.SerializerSettings;

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSerilogRequestLogging();

app.UseRouting();
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseAuthorization();
app.UseRouting();

app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.UseAuthorization();

app.Run();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application failed to start");
}
finally
{
Log.CloseAndFlush();
}
public partial class Program
{
}
Loading

0 comments on commit cf90756

Please sign in to comment.