我想使用 appsettings.json 配置 Application Insights 日志记录级别,就像我为 ASP.NET Core Web 应用程序所做的那样。
默认情况下,Application Insights SDK 添加“警告”日志记录级别筛选器,如下图所示。
我已读到,要配置 Application Insights 日志记录,使用
Logging.LogLevel.Default:
设置默认日志记录级别是不够的,必须明确指定:Logging.ApplicationInsights.LogLevel.Default:
。
但是,即使使用显式配置,我仍然观察到默认的“警告”过滤器,并且我需要在
ConfigureLogging()
中手动将其删除。
我做错了什么?
程序.cs:
var host = new HostBuilder()
.ConfigureFunctionsWebApplication((context, builder) => { })
.ConfigureAppConfiguration((context, builder) =>
{
var environment = context.Configuration.GetValue<string>("ENVIRONMENT", "development");
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
})
...
.ConfigureLogging(builder =>
{
builder.Services.Configure<LoggerFilterOptions>(options =>
{
// Default ApplicationInsights logging filter
LoggerFilterRule defaultRule = options.Rules.FirstOrDefault(rule => rule.ProviderName
== "Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider");
if (defaultRule is not null)
{
options.Rules.Remove(defaultRule);
}
});
builder.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information);
})
.Build();
appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Information"
}
}
}
}
使用
appsettings.json
在隔离的 Azure 功能中配置应用程序洞察。
appsettings.json
{
"AllowedHosts": "*",
"ApplicationInsights": {
"InstrumentationKey": "884669a2-08ea-46d3-9fe1-104311129c82"
}
}
注意:您还可以在
appsettings.json
中配置日志级别。
程序.cs:
var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureAppConfiguration((context, config) =>
{
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureServices((context, services) =>
{
var configuration = context.Configuration;
services.AddApplicationInsightsTelemetryWorkerService(options =>
{
options.ConnectionString = configuration["ApplicationInsights:InstrumentationKey"];
});
}).ConfigureLogging(logging =>
{
loggingBuilder.AddApplicationInsights();
loggingBuilder.SetMinimumLevel(LogLevel.Error);
})
.Build();
host.Run();
函数.cs:
[Function("Function1")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
{
_logger.LogInformation("This is an INFORMATION log message.");
_logger.LogWarning("This is a WARNING log message.");
_logger.LogError("This is an ERROR log message.");
_logger.LogTrace("This is a TRACE log message.");
_logger.LogDebug("This is a DEBUG log message.");
_logger.LogCritical("This is a CRITICAL log message.");
return new OkObjectResult("Welcome to Azure Functions!");
}
查询:
union isfuzzy=true
availabilityResults,
requests,
exceptions,
pageViews,
traces,
customEvents,
dependencies
| where timestamp > datetime("2024-09-22T12:09:27.658Z") and timestamp < datetime("2024-09-23T12:09:27.658Z")
| order by timestamp desc
| take 100