0

我正在将net4.8应用程序转移到net50,其中一部分工作是将日志记录从 重构Microsoft.EnterpriseLibraryILogger。我想将现有的结构化日志数据传递给 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);
}

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

CustomLogEntry接口的TState参数也是如此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似乎都与(在这种情况下)的TState参数有任何联系。ILogger.LogCustomLogEntry

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

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,但这感觉就像我在糖上加糖,并且在从 ILogger 到 Application Insight 遥测的映射中遗漏了一些东西。

4

1 回答 1

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);

您可以参考 手动记录一些额外的自定义遥测数据和使用 Azure Application Insights 记录自定义遥测数据

于 2021-07-29T13:29:17.643 回答