[英]How to Flush Application Insights in a ILogger
我有一個使用應用程序洞察的 Windows 控制台應用程序。 我使用Microsoft.Extensions.DependencyInjection
來設置我的類並添加ILogger
。
如果出現異常,我想將此記錄到 Application Insights。 但是由於 Application Insights 不會立即發送跟蹤,我想刷新日志。
有沒有辦法觸發ILogger
背后的 Application Insights 刷新?
static async Task Main(string[] args)
{
ServiceProvider serviceProvider = ConfigureServices();
var program = serviceProvider.GetService<Program>();
await program.Run();
}
public Program(ILogger<Program> logger)
{
this.logger = logger;
}
private static ServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
services
.AddLogging(opt =>
{
opt.AddConsole();
opt.AddApplicationInsights();
})
.AddTransient<Program>()
return services.BuildServiceProvider();
}
public async Task Run()
{
try
{
do.stuff()
}
catch (Exception e)
{
logger.LogError(e, "Exception occured");
// How to flush Application insights here
// Need to wait for Flush (see https://docs.microsoft.com/en-us/azure/azure-monitor/app/console)
await Task.Delay(1000);
throw;
}
}
請嘗試使用InMemoryChannel.Flush
方法,代碼示例如下:
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace ConsoleApp3netcore
{
class Program
{
private readonly ILogger logger;
static InMemoryChannel channel = new InMemoryChannel();
static async Task Main(string[] args)
{
ServiceProvider serviceProvider = ConfigureServices();
var program = serviceProvider.GetService<Program>();
await program.Run();
}
public Program(ILogger<Program> logger)
{
this.logger = logger;
}
private static ServiceProvider ConfigureServices()
{
var services = new ServiceCollection();
services.Configure<TelemetryConfiguration>(
(config) =>
{
config.TelemetryChannel = channel;
}
);
services
.AddLogging(opt =>
{
opt.AddConsole();
opt.AddApplicationInsights();
})
.AddTransient<Program>();
return services.BuildServiceProvider();
}
public async Task Run()
{
try
{
throw new Exception("my exception 111");
}
catch (Exception e)
{
logger.LogError(e, "Exception occured");
// How to flush Application insights here
channel.Flush();
await Task.Delay(1000);
throw;
}
}
}
}
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.