扩展 ApplicationInsights 日志遥测

时间:2021-07-28 12:23:02

标签: azure-application-insights telemetry ilogger

我正在将 net4.8 应用程序转移到 net50,其中一部分工作是将日志记录从 Microsoft.EnterpriseLibrary 重构为 ILogger。我想将现有的结构化日志数据传递给 ApplicationInsights。

调用:

logger.LogInformation("My message called with {p1} and {p2}", p1, p2);

产生 Application Insights 数据,包括 p1p2 的自定义维度 - 是的。

调用:

logger.Log(LogLevel.Information, 
  new EventId(127, "CustomLog"), 
  new CustomLogEntry(), 
  null, 
  (entry, ex) => { return "Testing custom"; });

哪里:

public class CustomLogEntry
{
    public int Id { get; set; } = 128;
    public string Name { get; set; } = Guid.NewGuid().ToString();
    public DateTimeOffset Expiration { get; set; } = DateTimeOffset.UtcNow.AddDays(1);
}

在 Application Insights 中不产生任何 CustomLogEntry 属性。

<块引用>

所以 CustomLogEntryTState 接口的 ILogger.Log 参数。这只是一个模拟;我真正想利用的是相当于 Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry

我的下一步是设置自定义 ITelemetryInitializer 以将 CustomLogEntry 属性添加到我的 ITelemetry

public class EventTelemetryInitializer : ITelemetryInitializer
{

    public EventTelemetryInitializer()
    { }

    public void Initialize(ITelemetry telemetry)
    {
        var trace = telemetry as TraceTelemetry;
        if (trace == null) return;
        trace.Properties.Add("Custom", "something");
            
    }
}

当我在 EventTelemetryInitializer.Initialize 方法中调试时,telemetry 参数的任何部分似乎都与 TStateILogger.Log 参数没有任何联系(在本例中为 {{ 1}}).

我必须使用格式将自定义维度传递到 Application Insights 吗?例如,而不是:

CustomLogEntry

使用:

logger.Log(LogLevel.Information, new EventId(127, "CustomLog"), new CustomLogEntry(), null, (entry, ex) => { return "Testing custom"; });

如果是这样,我倾向于为 var entry = new CustomLogEntry(); logger.LogInformation("Testing custom {Name}, {Expiration}, {Id}", entry.Name, entry.Expiration, entry.Id); 发明一些扩展糖,但这感觉就像我在糖上加糖,并且在从 ILogger 到 Application Insight 遥测的映射中遗漏了一些东西。< /p>

1 个答案:

答案 0 :(得分:0)

当您使用独立包时,TelemetryClient 不会注入到 DI 容器中,因此您需要创建 TelemetryClient 的新实例并使用与记录器提供程序相同的配置,如以下代码所示。这可确保对所有自定义遥测以及来自 ILogger 的遥测使用相同的配置。

public class MyController : ApiController
{
   // This TelemetryClient can be used to track additional telemetry using TrackXXX() api.
   private readonly TelemetryClient _telemetryClient;
   private readonly ILogger _logger;

   public MyController(IOptions<TelemetryConfiguration> options, ILogger<MyController> logger)
   {
        _telemetryClient = new TelemetryClient(options.Value);
        _logger = logger;
   }  
}

ApplicationInsightsLoggerProvider 捕获 ILogger 日志并从中创建 TraceTelemetry。如果将 Exception 对象传递给 ILogger 上的 Log 方法,则会创建 ExceptionTelemetry 而不是 TraceTelemetry。这些遥测项目可以在与 Application Insights 的任何其他 TraceTelemetry 或 ExceptionTelemetry 相同的位置找到,包括门户、分析或 Visual Studio 本地调试器。

如果您希望始终发送 TraceTelemetry,请使用以下代码段:

builder.AddApplicationInsights(
    options => options.TrackExceptionsAsExceptionTelemetry = false);

可以参考 Log some additional custom telemetry manuallyRecording custom telemetry with Azure Application Insights

相关问题