The*_*Guy 1 c# azure-web-sites azure-application-insights asp.net-core
我正在使用Microsoft.ApplicationInsights.AspNetCore(https://www.nuget.org/packages/Microsoft.ApplicationInsights.AspNetCore)。
我通过在Programs.cs和启动类中添加.UseApplicationInsights()来启用应用程序见解:
loggerFactory.AddApplicationInsights(app.ApplicationServices);
Run Code Online (Sandbox Code Playgroud)
一切正常,我可以在应用程序洞察中查看请求,但是当我尝试记录错误时(例如在控制器中):
_logger.LogError("My Error Log");
_logger.LogError("Test", new Exception("Test"));
Run Code Online (Sandbox Code Playgroud)
两者均记录为跟踪事件,而不是应用程序见解中的异常。
我如何使它记录为例外?
如果您想将错误记录为“异常”,请_logger.LogError("Test", new Exception("Test"));
更改此行代码。
将其更改为_logger.LogError(new Exception(), "test");
,这意味着new Exception()
应该是第一个参数。
您还可以通过右键单击您的项目->添加-> Application Insights Telemetry添加Application Insights SDK,这对于自动执行某些操作(即添加.UseApplicationInsights() in Programs.cs
)非常有用:
我还发布了测试步骤:
1.如上所述添加应用程序见解SDK
2.添加loggerFactory.AddApplicationInsights(app.ApplicationServices,LogLevel.Information);
Startup.cs-> Configure()方法,代码如下:
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);
}
Run Code Online (Sandbox Code Playgroud)
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.";
}
}
Run Code Online (Sandbox Code Playgroud)
由于Microsoft.ApplicationInsights.AspNet v2.7
问题和接受的答案是过时的,因为调用AddApplicationInsights
上ILoggerFactory
现在已经过时。
请参考官方文档。
文档中的要点:
ApplicationInsightsLoggerProvider
默认情况下启用。appsettings.json
(如果您确实需要,可以通过编程方式) "Logging": {
"LogLevel": {
"Default": "Warning"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Error"
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2108 次 |
最近记录: |