UPDATE
By shutting down the application using ctrl + c in the console, the "finally" block of program.cs is executed, logs are flushed and saved to Application Insights. However, if the application is stopped abruptly, (browser window closed for example) logs are not sent to Application Insights and the information is lost, which isn't ideal. Does anyone have method or suggestion to make logs flush more frequently or how to safeguard in the event of the application terminating unexpectedly
ORIGINAL
I'm trying to configure C# web application project to log files to Application Insights using Serilog. I have followed the documentation to configure the logger to read for the appsetting.json file and have been able to implement other sinks to write logs to the console, file SEQ etc, but the Application Insights won't work. Request data is available on application insights using the configuration below
Program.cs
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateBootstrapLogger();
Log.Information("Application Starting up");
try
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddApplicationInsightsTelemetry();
builder.Host.UseSerilog();
// Add services to the container.
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/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.UseAuthorization();
app.MapRazorPages();
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "the application failed to start correctly");
}
finally
{
Log.CloseAndFlush();
}
appsettings.json
{
"ApplicationInsights": {
"connectionString": "MyConnectionString"
},
"Serilog": {
"Using": [
"Serilog.Sinks.ApplicationInsights"
],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"System": "Information"
}
},
"WriteTo": [
{
"Name": "ApplicationInsights",
"Args": {
"connectionString": "*MyConnectionString",
"telemetryConverter": "Serilog.Sinks.ApplicationInsights.TelemetryConverters.TraceTelemetryConverter, Serilog.Sinks.ApplicationInsights",
}
}
,
{
"Name": "Console"
}
],
"Enrich": [ "FromLogcontext", "WithMachineName", "WithProcessId", "WithThreadId" ]
}
}
Requests are being saved to application insights, but I can't get the logs (traces) or exceptions to be saved. Am I missing something??
Edit I have log events written in the index like so
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
try
{
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
_logger.LogCritical("Serilog: Testing log critical");
throw new Exception("Serilog iLogger Exception");
}
else
{
_logger.LogWarning("Serilog: The value of i is {LoopCountValue}", i);
_logger.LogWarning("Serilog: Testing log warning");
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "exception in the index Get call");
}
}
}
Adding .csproj file
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.AspNetCore" Version="6.1.0"/>
<PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.ApplicationInsights" Version="4.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.21.0" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.21.0" />
<PackageReference Include="Serilog.Enrichers.AspNetCore" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.Seq" Version="5.2.2" />
</ItemGroup>
</Project>