[英]How to Flush Application Insights in a ILogger
I have a windows console application using application insights.我有一个使用应用程序洞察的 Windows 控制台应用程序。 I use the
Microsoft.Extensions.DependencyInjection
to set up my class and add the ILogger
.我使用
Microsoft.Extensions.DependencyInjection
来设置我的类并添加ILogger
。
In a case of an exception I want to log this to Application Insights.如果出现异常,我想将此记录到 Application Insights。 But since Application Insights does send traces not immediately I want to Flush the log.
但是由于 Application Insights 不会立即发送跟踪,我想刷新日志。
Is there an way to trigger the Flush of Application Insights behind a ILogger
?有没有办法触发
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;
}
}
Please try use the method InMemoryChannel.Flush
, code sample as blow:请尝试使用
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;
}
}
}
}
Hope it helps.希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.