Skip to content

Commit

Permalink
Configure logging with appsettings.json
Browse files Browse the repository at this point in the history
Use appsettings.json to configure logging instead of code.
  • Loading branch information
martincostello committed Nov 26, 2023
1 parent 0e93784 commit 2ac07a3
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 79 deletions.
3 changes: 3 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
<PackageVersion Include="MartinCostello.Testing.AwsLambdaTestServer" Version="0.8.0" />
<PackageVersion Include="Microsoft.ApplicationInsights" Version="2.21.0" />
<PackageVersion Include="Microsoft.AspNetCore.WebUtilities" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="8.0.0" />
Expand Down
55 changes: 24 additions & 31 deletions src/LondonTravel.Skill/AlexaFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
using MartinCostello.LondonTravel.Skill.Intents;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
using Microsoft.Extensions.Options;

namespace MartinCostello.LondonTravel.Skill;

Expand Down Expand Up @@ -96,28 +96,42 @@ public Task<bool> InitializeAsync()
return Task.FromResult(true);
}

/// <summary>
/// Configures the <see cref="ConfigurationBuilder"/> to use.
/// </summary>
/// <param name="builder">The configuration builder to configure.</param>
protected virtual void Configure(ConfigurationBuilder builder)
{
builder.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables();
}

/// <summary>
/// Configures the <see cref="IServiceCollection"/> to use.
/// </summary>
/// <param name="services">The service collection to configure.</param>
protected virtual void ConfigureServices(IServiceCollection services)
{
services.AddLogging((builder) =>
{
builder.SetMinimumLevel(LogLevel.Information)
.AddFilter(FilterLogs)
.AddJsonConsole();
});
var builder = new ConfigurationBuilder();

services.AddHttpClients();
Configure(builder);

var configuration = builder.Build();

services.AddOptions();
services.Configure<SkillConfiguration>(configuration.GetSection("Skill"));

services.TryAddSingleton((_) => SkillConfiguration.CreateDefaultConfiguration());
services.AddLogging((builder) => builder.AddJsonConsole());

services.AddHttpClients();

services.AddSingleton<AlexaSkill>();
services.AddSingleton<FunctionHandler>();
services.AddSingleton<IntentFactory>();
services.AddSingleton((_) => TelemetryConfiguration.CreateDefault());
services.AddSingleton(CreateTelemetryClient);
services.AddSingleton((p) => p.GetRequiredService<IOptions<SkillConfiguration>>().Value);
services.AddSingleton(configuration);

services.AddSingleton<EmptyIntent>();
services.AddSingleton<HelpIntent>();
Expand Down Expand Up @@ -162,27 +176,6 @@ private static TelemetryClient CreateTelemetryClient(IServiceProvider servicePro
return new TelemetryClient(configuration);
}

/// <summary>
/// Filters the Lambda logs.
/// </summary>
/// <param name="name">The name of the log.</param>
/// <param name="level">The log level.</param>
/// <returns>
/// <see langword="true"/> to log the message; otherwise <see langword="false"/>.
/// </returns>
private static bool FilterLogs(string name, LogLevel level)
{
if (level < LogLevel.Warning &&
(name.StartsWith("System.", StringComparison.Ordinal) ||
name.StartsWith("Microsoft.", StringComparison.Ordinal) ||
name.StartsWith("Polly", StringComparison.Ordinal)))
{
return false;
}

return true;
}

/// <summary>
/// Creates the <see cref="ServiceProvider"/> to use.
/// </summary>
Expand Down
4 changes: 4 additions & 0 deletions src/LondonTravel.Skill/LondonTravel.Skill.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
<PackageReference Include="Amazon.Lambda.Serialization.Json" />
<PackageReference Include="Microsoft.ApplicationInsights" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
Expand All @@ -29,6 +32,7 @@
<Compile Update="Strings.Designer.cs" AutoGen="True" DependentUpon="Strings.resx" DesignTime="True" />
<EmbeddedResource Update="Strings.resx" Generator="ResXFileCodeGenerator" LastGenOutput="Strings.Designer.cs" />
<EmbeddedResource Update="Strings.*.resx" DependentUpon="Strings.resx" />
<None Include="appsettings.json" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup Condition=" '$(RuntimeIdentifier)' == 'linux-arm64' ">
<PackageReference Include="Microsoft.ICU.ICU4C.Runtime" />
Expand Down
27 changes: 0 additions & 27 deletions src/LondonTravel.Skill/SkillConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,31 +37,4 @@ public sealed class SkillConfiguration
/// Gets or sets a value indicating whether to validate the skill's Id.
/// </summary>
public bool VerifySkillId { get; set; }

/// <summary>
/// Create a default instance of the skill configuration.
/// </summary>
/// <returns>
/// The default <see cref="SkillConfiguration"/> to use.
/// </returns>
public static SkillConfiguration CreateDefaultConfiguration()
{
if (!bool.TryParse(GetEnvironmentVariable("VERIFY_SKILL_ID"), out bool verifySkillId))
{
verifySkillId = false;
}

return new SkillConfiguration()
{
ApplicationInsightsConnectionString = GetEnvironmentVariable("APPINSIGHTS_CONNECTIONSTRING"),
SkillApiUrl = GetEnvironmentVariable("SKILL_API_HOSTNAME"),
SkillId = GetEnvironmentVariable("SKILL_ID"),
TflApplicationId = GetEnvironmentVariable("TFL_APP_ID"),
TflApplicationKey = GetEnvironmentVariable("TFL_APP_KEY"),
VerifySkillId = verifySkillId,
};
}

private static string GetEnvironmentVariable(string name)
=> Environment.GetEnvironmentVariable(name) ?? string.Empty;
}
18 changes: 18 additions & 0 deletions src/LondonTravel.Skill/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Polly": "Warning",
"System": "Warning"
}
},
"Skill": {
"ApplicationInsightsConnectionString": "",
"SkillApiUrl": "",
"SkillId": "",
"TflApplicationId": "",
"TflApplicationKey": "",
"VerifySkillId": false
}
}
30 changes: 10 additions & 20 deletions test/LondonTravel.Skill.Tests/FunctionTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Alexa.NET.Response;
using JustEat.HttpClientInterception;
using MartinCostello.Logging.XUnit;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -36,26 +37,11 @@ protected virtual ResponseBody AssertResponse(SkillResponse actual, bool? should
return actual.Response;
}

protected virtual SkillConfiguration CreateConfiguration()
{
var config = SkillConfiguration.CreateDefaultConfiguration();

config.ApplicationInsightsConnectionString = "InstrumentationKey=my-application-insights-key;IngestionEndpoint=https://northeurope-0.in.applicationinsights.azure.com/;LiveEndpoint=https://northeurope.livediagnostics.monitor.azure.com/";
config.SkillApiUrl = "https://londontravel.martincostello.local/";
config.SkillId = "my-skill-id";
config.TflApplicationId = "my-tfl-app-id";
config.TflApplicationKey = "my-tfl-app-key";
config.VerifySkillId = true;

return config;
}

protected virtual async Task<AlexaFunction> CreateFunctionAsync()
{
SkillConfiguration config = CreateConfiguration();
var function = new TestAlexaFunction(config, Interceptor, OutputHelper);
var function = new TestAlexaFunction(Interceptor, OutputHelper);

await function.InitializeAsync();
_ = await function.InitializeAsync();

return function;
}
Expand Down Expand Up @@ -134,16 +120,20 @@ protected virtual SkillRequest CreateRequest<T>(T request = null)
}

private sealed class TestAlexaFunction(
SkillConfiguration config,
HttpClientInterceptorOptions options,
ITestOutputHelper outputHelper) : AlexaFunction, ITestOutputHelperAccessor
{
public ITestOutputHelper OutputHelper { get; set; } = outputHelper;

protected override void Configure(ConfigurationBuilder builder)
{
base.Configure(builder);
builder.AddJsonFile("testsettings.json");
}

protected override void ConfigureServices(IServiceCollection services)
{
services.AddLogging((builder) => builder.AddXUnit(this).SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug));
services.AddSingleton(config);
services.AddLogging((builder) => builder.AddXUnit(this));
services.AddSingleton<IHttpMessageHandlerBuilderFilter, HttpRequestInterceptionFilter>(
(_) => new HttpRequestInterceptionFilter(options));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<PackageReference Include="xunit.runner.visualstudio" />
</ItemGroup>
<ItemGroup>
<Content Include="xunit.runner.json;Bundles\*.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="testsettings.json;xunit.runner.json;Bundles\*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<PropertyGroup>
<CollectCoverage>true</CollectCoverage>
Expand Down

0 comments on commit 2ac07a3

Please sign in to comment.