We have a .net6 web API and worker project that we are trying to leverage Serilog to log to app insights.
We have an extension method existing in a common class library that is used in both solutions:
/// <summary>
/// Extension IHostBuilder method for configuring logging in projects.
/// </summary>
/// <param name="hostBuilder">IHostbuilder.</param>
/// <returns>IHostBuilder.</returns>
public static IHostBuilder ConfigureLogging(this IHostBuilder hostBuilder)
{
hostBuilder.UseSerilog((hostingContext, loggerConfiguration) =>
{
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration);
});
return hostBuilder;
}
We use this in the program.cs file
var builder = WebApplication.CreateBuilder(args); builder.Host.ConfigureLogging();
The following packages are installed in the common library and in the api library
<ItemGroup><PackageReference Include="Serilog.AspNetCore" Version="5.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="3.3.0" /> <PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="3.1.0" /> </ItemGroup>
The above packages are also installed in the API project.
We have it picking up the instrumentation key when placed inside the serilog block.. however this is discouraged as per their guidance here:https://github.com/serilog-contrib/serilog-sinks-applicationinsights#configuring-with-readfromconfiguration - "As mentioned above you can also pass an instrumentation key but it's actively discouraged"
We have the following configuration in appsettings.json in the API project as an example and it works when we reference the instrumentation key inside as shown below:
{
"Serilog": {
"Using": [
"Serilog.Sinks.ApplicationInsights"
],
"MinimumLevel": {
"Default": "Information",
"Override": {
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "ApplicationInsights",
"Args": {
"instrumentationkey: "<key goes here>",
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights"
}
}
],
"Enrich": [ "FromLogContext" ],
"Properties": {
"Application": "Solution.Api"
}
}
}
We can also get it working through using environment variables, by adding the following into launchsettings.json:
"Solution.Api": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7194;http://localhost:5194",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"APPINSIGHTS_INSTRUMENTATIONKEY": "<Insert instrumentation key>"
}
},
Ultimately, neither of these approaches seem correct and we want to have the instrumentation key in appSettings decoupled from serilog config as per best practice It seems this is a known issue and may be to do with .net6 https://github.com/serilog-contrib/serilog-sinks-applicationinsights/issues/176 Wondering if anyone knows what the issue is/we are missing?