我注意到我的 .net core 应用程序正在记录请求,但没有跟踪我的 azure 应用程序见解。
我正在我的 Startup.cs
中设置应用程序洞察services.AddApplicationInsightsTelemetry(options =>
{
options.InstrumentationKey = Configuration["ApplicationInsightsInstrumentationKey"];
});
我像这样在我的控制器中注入 ILogger
private readonly ILogger<HealthCheckController> _logger;
public HealthCheckController(ILogger<HealthCheckController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult HealthCheck()
{
// Custom EventId for logging
var eventId = EventDefinition.TestMicroservice.HealthCheckController.HealthCheck;
_logger.LogInformation(eventId, "Test Microservice health check successful.");
return Ok("Test Microservice is running!");
}
我错过了什么吗? 我多次点击控制器,并且看到请求被记录,但在跟踪下找不到我的自定义日志消息。
所以我发现,尽管我想使用 ILogger,但我仍然能够注入 TelemetryClient。 当我保留上面的代码时,我必须添加 .ConfigureLogging
protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new ServiceInstanceListener[]
{
new ServiceInstanceListener(serviceContext =>
new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
return new WebHostBuilder()
.UseKestrel()
.ConfigureServices(
services => services
.AddSingleton<StatelessServiceContext>(serviceContext))
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((context, config) =>
{
var configurationPackage = FabricRuntime.GetActivationContext()?.GetConfigurationPackageObject("Config");
// Add Key Vault
var kv = configurationPackage.Settings.Sections[KeyVaultOptions.Position].Parameters;
var credential = new ClientSecretCredential(kv["TenantId"].Value, kv["ClientId"].Value, kv["ClientSecret"].Value);
var client = new SecretClient(new Uri(kv["Url"].Value), credential);
config.AddAzureKeyVault(client, new AzureKeyVaultConfigurationOptions());
config.Build();
})
.ConfigureLogging((context, logging) =>
{
logging.AddApplicationInsights(
context.Configuration["ApplicationInsightsInstrumentationKey"]);
logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Trace);
})
.UseStartup<Startup>()
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseUrls(url)
.Build();
}))
};
默认情况下,ApplicationInsights 仅收集警告或更高级别的警告。您可以按照此处的文档进行更改:https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#how-do-i-customize-ilogger-logs-收藏
这对我有帮助:
.ConfigureLogging((context, logging) =>
{
logging.AddApplicationInsights(
context.Configuration["ApplicationInsightsInstrumentationKey"]);
logging.AddFilter<ApplicationInsightsLoggerProvider>("", LogLevel.Information);
})