The*_*Guy 7 azure azure-application-insights
我在我的应用程序中为Application Insights编写了一个自定义记录器.在Azure门户中查看App Insights时,我没有看到任何异常或任何事件.这是logger类代码,当我调试代码时,我确实看到了一个分配给InstrumentationKey属性的键,任何想法我在这里做错了什么?我是否需要将其他信息附加到客户端或配置?
public class AppInsightsLogger:ILogger
{
private TelemetryClient ai;
public AppInsightsLogger()
{
ai = new TelemetryClient();
if (string.IsNullOrEmpty(ai.InstrumentationKey))
{
// attempt to load instrumentation key from app settings
var appSettingsTiKey = AppSettings.InsightsKey;
if (!string.IsNullOrEmpty(appSettingsTiKey))
{
TelemetryConfiguration.Active.InstrumentationKey = appSettingsTiKey;
ai.InstrumentationKey = appSettingsTiKey;
}
else
{
throw new Exception("Could not find instrumentation key for Application Insights");
}
}
}
public void LogException(Exception ex)
{
ai.TrackException(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*kou 10
我创建了一个新的控制台应用程序,安装了最新的稳定的ApplicationInsights SDK并且几乎保留了您的示例,但有一点但重要的区别 - 在调用TrackException或添加TelemetryClient.Flush()之后我要么让它等待关闭
namespace logtest
{
class Program
{
static void Main(string[] args)
{
AppInsightsLogger logger = new AppInsightsLogger();
logger.LogException(new InvalidOperationException("Is data showing?"));
// either wait for a couple of minutes for the batch to be sent of add ai.Flush() after ai.TrackException() to send the batch immediately
Console.ReadLine();
}
}
public class AppInsightsLogger
{
private TelemetryClient ai;
public AppInsightsLogger()
{
ai = new TelemetryClient();
if (string.IsNullOrEmpty(ai.InstrumentationKey))
{
// attempt to load instrumentation key from app settings
var appSettingsTiKey = "<ikey>";
if (!string.IsNullOrEmpty(appSettingsTiKey))
{
TelemetryConfiguration.Active.InstrumentationKey = appSettingsTiKey;
ai.InstrumentationKey = appSettingsTiKey;
}
else
{
throw new Exception("Could not find instrumentation key for Application Insights");
}
}
}
public void LogException(Exception ex)
{
ai.TrackException(ex);
// ai.Flush();
}
}
}
Run Code Online (Sandbox Code Playgroud)
首先,我可以看到在Visual Studio调试输出窗口中发送的遥测项目:

然后我可以看到遥测器离开我的机器在Fiddler,我也可以看到它被我们的数据收集终点成功接受.

最后我可以在门户网站上看到它:
如今,这个问题和接受的答案已经过时了。现代方法是添加Microsoft.ApplicationInsights.AspNetNuGet 包,它具有开箱即用的日志记录功能。
请参考官方文档。
文档中的要点:
ApplicationInsightsLoggerProvider 默认情况下启用。appsettings.json(如果您确实需要,可以通过编程方式) "Logging": {
"LogLevel": {
"Default": "Warning"
},
"ApplicationInsights": {
"LogLevel": {
"Default": "Error"
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7708 次 |
| 最近记录: |