为什么当我注入
ILogger<MyClassName>
并调用 Logger.LogInformation
时,我在 Application Insights 中看不到这一点,但当我调用 Logger.LogError
时却看到了?
这是我的代码
public async ValueTask DeleteMessageAsync(string chatId, int messageId)
{
Logger.LogInformation(
"Deleting message: {chatId} {messageId}",
chatId,
messageId);
try
{
await TelegramBotClient.DeleteMessageAsync(chatId, messageId);
}
catch (ApiRequestException ex)
when (ex.ErrorCode == (int)HttpStatusCode.BadRequest)
{
Logger.LogError(ex, "Could not Delete message");
}
}
这是我的
host.json
文件的日志记录部分
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
},
"enableLiveMetricsFilters": true
},
"DurableTask.AzureStorage": "Information",
"DurableTask.Core": "Information"
}
这是我的 Azure 函数应用程序的主机构建器
IHost host = new HostBuilder()
.AddServiceDefaults(useOtlpExporter: false, isDevelopment: true)
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
services.AddSingleton<ITelegramBroadcastService, TelegramBroadcastService>();
services.AddSingleton<IAuthorizationService, AuthorizationService>();
services.AddDurableTaskClient(x =>
{
});
services.AddAzureClients(clientBuilder =>
{
clientBuilder.AddBlobServiceClient(Environment.GetEnvironmentVariable("AzureWebJobsStorage"));
});
})
.ConfigureAppConfiguration((context, config) =>
{
if (context.HostingEnvironment.IsDevelopment())
config.AddUserSecrets<Program>();
})
.Build();
host.Run();
AddServiceDefaults
扩展是新 Aspire 应用程序中默认添加的扩展。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
namespace Microsoft.Extensions.Hosting;
public static class Extensions
{
public static T AddServiceDefaults<T>(this T builder, bool useOtlpExporter, bool isDevelopment)
where T : IHostBuilder
{
builder.ConfigureOpenTelemetry(
useOtlpExporter: useOtlpExporter,
isDevelopment: isDevelopment);
builder.AddDefaultHealthChecks();
builder.AddServiceDiscovery();
return builder;
}
public static T AddServiceDiscovery<T>(this T builder)
where T : IHostBuilder
{
builder.ConfigureServices(services =>
{
services.AddServiceDiscovery();
});
return builder;
}
public static T ConfigureHttpClientDefaults<T>(this T builder)
where T : IHostBuilder
{
builder.ConfigureServices(services =>
{
services.ConfigureHttpClientDefaults(http =>
{
// Turn on resilience by default
http.AddStandardResilienceHandler();
// Turn on service discovery by default
http.UseServiceDiscovery();
});
});
return builder;
}
public static T ConfigureOpenTelemetry<T>(this T builder, bool useOtlpExporter, bool isDevelopment)
where T : IHostBuilder
{
builder.ConfigureLogging(logging =>
{
logging.AddOpenTelemetry(telemetry =>
{
telemetry.IncludeFormattedMessage = true;
telemetry.IncludeScopes = true;
});
});
builder.ConfigureServices(services =>
{
services.AddOpenTelemetry()
.WithMetrics(metrics =>
{
metrics.AddRuntimeInstrumentation()
.AddBuiltInMeters();
})
.WithTracing(tracing =>
{
if (isDevelopment)
{
// We want to view all traces in development
tracing.SetSampler(new AlwaysOnSampler());
}
tracing.AddAspNetCoreInstrumentation()
.AddGrpcClientInstrumentation()
.AddHttpClientInstrumentation();
});
});
builder.AddOpenTelemetryExporters(useOtlpExporter);
return builder;
}
private static T AddOpenTelemetryExporters<T>(this T builder, bool useOtlpExporter)
where T : IHostBuilder
{
builder.ConfigureServices(services =>
{
if (useOtlpExporter)
{
services.Configure<OpenTelemetryLoggerOptions>(logging => logging.AddOtlpExporter());
services.ConfigureOpenTelemetryMeterProvider(metrics => metrics.AddOtlpExporter());
services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.AddOtlpExporter());
}
// Uncomment the following lines to enable the Prometheus exporter (requires the OpenTelemetry.Exporter.Prometheus.AspNetCore package)
//services
// .AddOpenTelemetry();
// .WithMetrics(metrics => metrics.AddPrometheusExporter());
// Uncomment the following lines to enable the Azure Monitor exporter (requires the Azure.Monitor.OpenTelemetry.Exporter package)
//services
// .AddOpenTelemetry()
// .UseAzureMonitor();
});
return builder;
}
public static T AddDefaultHealthChecks<T>(this T builder)
where T : IHostBuilder
{
builder.ConfigureServices(services =>
{
services.AddHealthChecks()
// Add a default liveness check to ensure app is responsive
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
});
return builder;
}
public static WebApplication MapDefaultHealthCheckEndpoints(this WebApplication app)
{
// Uncomment the following line to enable the Prometheus endpoint (requires the OpenTelemetry.Exporter.Prometheus.AspNetCore package)
// app.MapPrometheusScrapingEndpoint();
// All health checks must pass for app to be considered ready to accept traffic after starting
app.MapHealthChecks("/health");
// Only health checks tagged with the "live" tag must pass for app to be considered alive
app.MapHealthChecks("/alive", new HealthCheckOptions
{
Predicate = r => r.Tags.Contains("live")
});
return app;
}
private static MeterProviderBuilder AddBuiltInMeters(this MeterProviderBuilder meterProviderBuilder) =>
meterProviderBuilder.AddMeter(
"Microsoft.AspNetCore.Hosting",
"Microsoft.AspNetCore.Server.Kestrel",
"System.Net.Http");
}
以下是根据
portal.azure.com
应用的应用程序设置
{
"deployment_branch": "master",
"SCM_TRACE_LEVEL": "Verbose",
"SCM_COMMAND_IDLE_TIMEOUT": "60",
"SCM_LOGSTREAM_TIMEOUT": "7200",
"SCM_BUILD_ARGS": "",
"AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=...AccountKey=...=;EndpointSuffix=core.windows.net",
"AzureWebJobsSecretStorageType": "Blob",
"WEBSITE_USE_PLACEHOLDER_DOTNETISOLATED": "1",
"APPLICATIONINSIGHTS_CONNECTION_STRING": "InstrumentationKey=...IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/",
"WEBSITE_SLOT_NAME": "Production",
"SCM_USE_LIBGIT2SHARP_REPOSITORY": "0",
"WEBSITE_SITE_NAME": "...",
"FUNCTIONS_EXTENSION_VERSION": "~4",
"WEBSITE_AUTH_ENABLED": "False",
"ScmType": "None",
"WEBSITE_RUN_FROM_PACKAGE": "1",
"FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
}
在你的
appsettings.json
:
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
如果根据您的环境有多个
appsettings.json
,请务必正确选择您的环境并编辑特定的 appsettings.json
。
例如,如果您处于
development
环境中,请确保在 appsettings.Development.json
中设置这些设置。