Reputation: 59
Hello I have encountered a rather strange problem with the logs in Azure Functions for application insights. I'm not getting the logging of scope values working. I've tried different settings and still can't achieve this. In WebApi application it works without problems
Program.cs
.ConfigureLogging((context, loggingBuilder) =>
{
loggingBuilder.AddApplicationInsights("...");
})
Host:
{
"version": "2.0",
"logging": {
"logLevel": {
"Default": "Trace",
"Microsoft.AspNetCore": "Warning"
},
"applicationInsights": {
"logLevel": {
"Default": "Information"
}
}
},
"extensions": {
"serviceBus": {
"prefetchCount": 32,
"messageHandlerOptions": {
"autoComplete": true,
"maxConcurrentCalls": 32,
"maxAutoRenewDuration": "00:30:00"
}
},
"eventHub": {
"maxBatchSize": 64,
"prefetchCount": 256,
"batchCheckpointFrequency": 1
}
}
}
Log:
using (_logger.BeginScope(new Dictionary<string, object> { ["Scope"] = "Test" }))
{
_logger.LogInformation("Import check requested started");
_logger.LogWarning("Test Warning");
}
Thanks a lot
Upvotes: 1
Views: 307
Reputation: 2646
To add log below warning level scope you need to add this in you Program.cs
file in .NET 8
.
.ConfigureLogging(logging =>
{
logging.Services.Configure<LoggerFilterOptions>(options =>
{
LoggerFilterRule defaultRule = options.Rules.FirstOrDefault(rule => rule.ProviderName
== "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider");
if (defaultRule is not null)
{
options.Rules.Remove(defaultRule);
}
});
})
.ConfigureAppConfiguration((hostContext, config) =>
{
config.AddJsonFile("host.json", optional: true);
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddApplicationInsights(console =>
{
console.IncludeScopes = true;
});
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
})
This worked for me:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
namespace Isolatedfunc
{
public class Function1
{
private readonly ILogger<Function1> _logger;
public Function1(ILogger<Function1> logger)
{
_logger = logger;
}
[Function("Function1")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route ="test")] HttpRequest req)
{
using (_logger.BeginScope(new Dictionary<string, Object> { ["Scope"] = "Test" }))
{
_logger.LogInformation("C# HTTP trigger function processed a request.");
_logger.LogTrace("Test Tracing");
_logger.LogWarning("Test Warning");
}
return new OkObjectResult("Welcome to Azure Functions!");
}
}
}
logLevel
is not supported inside "applicationInsights"
section in host.json
.
host.json
:
{
"version": "2.0",
"logging": {
"logLevel": {
"default": "Trace",
"Microsoft.AspNetCore": "Warning"
},
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
},
"enableLiveMetricsFilters": true
}
}
}
OUTPUT
:Upvotes: 1