I've been trying to set up Application Insights with an ASP.NET Core 2.0 application. While running my application locally, logs are showing up in Application Insights as expected. However, when deployed to an Azure App Service, while logs are being sent to the "requests" table in Application Insights, no logs are showing up in "exceptions" or "traces".
The only thing that seems to resolve this is adding the below line of code to Startup.Configure()
:
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Information);
The solution above is undesirable as we want to configure the log level differently by the environment, so a configuration-based solution would be preferred. Also, my guess is that the problem is configuration-related as it works fine locally. There is no special configuration that was done in Azure.
Here is the entire Startup.Configure()
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Information);
}
My Program.cs is as follows:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) => WebHost
.CreateDefaultBuilder(args)
.UseApplicationInsights()
.UseStartup<Startup>()
.Build();
}
appsettings.json (InstrumentationKey
replaced for privacy):
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Debug"
}
},
"Console": {
"LogLevel": {
"Default": "Debug"
}
},
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ApplicationInsights": {
"InstrumentationKey": "00000000-0000-0000-0000-000000000000"
}
}
Update: New instructions are here for correctly enabling log capture. https://learn.microsoft.com/en-us/azure/azure-monitor/app/ilogger
The correct way of enabling logging support is by using loggerFactory.AddApplicationInsights()
in Configure
method. When you run from Visual Studio, you don't need this line because VS does it under the covers for you. But it won't work when ran from outside VS, so please add loggerFactory.AddApplicationInsights
method.
https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Logging
To get different log level based on environment, use this line inside condition statements. Something like the following example.
if(env.IsDeveleopment())
{
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Debug);
}
else if(env.IsPreProduction())
{
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Verbose);
}
else
{
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Warning);
}