作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个使用应用程序洞察的 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://learn.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;
}
}
}
}
希望有帮助。
关于c# - 如何在 ILogger 中刷新应用程序洞察,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55531886/
我是一名优秀的程序员,十分优秀!