如果您想在应用洞察中将错误记录为异常,则应更改这行代码_logger.LogError("Test", new Exception("Test"));。
将其更改为_logger.LogError(new Exception(), "test");,这意味着new Exception()应该是第一个参数。
您可以通过右键单击您的项目 -> 添加 -> Application Insights Telemetry 添加应用程序洞察 SDK,这对于自动执行某些操作非常有用(即添加 .UseApplicationInsights() in Programs.cs):
我还发布了我的测试步骤:
1.如上所述添加应用洞察SDK
2.在Startup.cs -> Configure()方法中添加loggerFactory.AddApplicationInsights(app.ApplicationServices,LogLevel.Information);,代码如下:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
//Add this line of code
loggerFactory.AddApplicationInsights(app.ApplicationServices,LogLevel.Information);
}
3.然后在你想记录错误的地方:
public class AboutModel : PageModel
{
private ILogger _logger;
public AboutModel(ILogger<AboutModel> logger)
{
_logger = logger;
}
public string Message { get; set; }
public void OnGet()
{
_logger.LogInformation("it is just a test herexxxx");
//Only this format can log as exception
_logger.LogError(new Exception(), "it is a new Exceptionxxxx");
//it will log as trace
_logger.LogError("error logs xxx");
Message = "Your application description page.";
}
}
4.测试结果如下: