我想将异常记录到Application Insights。通过直接调用TelemetryClient.TrackException
,我成功地做到了这一点。但是,如果将来我想记录到其他平台,我希望在我的代码中抽象出这个部分,因此我只想坚持使用ILogger接口。
我发现你可以使用ILoggerFactory.AddApplicationInsights
(如这里实现),但无论我做什么,我都没有看到日志在ApplicationInsights中显示。
以下是我的代码:
Startup.cs
IConfigurationRoot Configuration { get; set; }
ILoggerFactory LoggerFactory { get; set; }
IServiceProvider ServiceProvider { get; set; }
public Startup( IHostingEnvironment hostingEnvironment, ILoggerFactory loggerFactory )
{
this.LoggerFactory = loggerFactory;
string configurationFilePath = "abc.json";
this.Configuration = new ConfigurationBuilder()
.SetBasePath( hostingEnvironment.ContentRootPath )
.AddJsonFile( configurationFilePath, optional: true, reloadOnChange: true )
.AddEnvironmentVariables()
.Build();
}
public void Configure(
IApplicationBuilder applicationBuilder,
IHostingEnvironment hostingEnvironment,
ILoggerFactory loggerFactory,
IServiceProvider serviceProvider )
{
this.ServiceProvider = serviceProvider;
loggerFactory.AddApplicationInsights( serviceProvider );
applicationBuilder.UseMvc();
}
public void ConfigureServices( IServiceCollection services )
{
services.AddApplicationInsightsTelemetry( this.Configuration );
services.AddMvc( .... // A bunch of options here ... )
}
然后,我尝试在我的控制器中像这样使用它:
ILogger<XController> Logger { get; set; }
public XController( ILogger<XController> logger )
{
this.Logger = logger;
}
[HttpPost]
[Route( "v3.0/abcd" )]
public async Task PostEvent( [FromBody] XEvent xEvent )
{
this.Logger.LogError( 0, new Exception( "1234" ), "1234" );
}
然而,我并没有看到与请求相关的任何异常。如果我将Logger.LogError
行替换为TelemetryClient.TrackException
(并首先创建TelemetryClient
),那么我可以毫无问题地看到异常。
我不知道我做错了什么,有人能帮忙吗?