我正在将net4.8
应用程序转移到net50
,其中一部分工作是将日志记录从 重构Microsoft.EnterpriseLibrary
为ILogger
。我想将现有的结构化日志数据传递给 ApplicationInsights。
调用这个:
logger.LogInformation("My message called with {p1} and {p2}", p1, p2);
生成 Application Insights 数据,包括p1
和p2
- 的自定义维度。
调用这个:
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.Log
CustomLogEntry
是否必须使用格式将自定义维度传递给 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 遥测的映射中遗漏了一些东西。