【发布时间】:2017-09-13 06:57:31
【问题描述】:
ILogger 接口只有一个 Log 方法:
void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter);
ApplicationInsights 为我提供了这样一个丰富的 api:
TrackMetric(string name, double value, IDictionary<string, string> properties = null);
TrackException(Exception exception, IDictionary<string, string> properties = null, IDictionary<string, double> metrics = null);
TrackTrace(string message, SeverityLevel severityLevel, IDictionary<string, string> properties);
我应该如何实现自定义 ILogger 并且仍然具有应用程序洞察力的所有功能?我能想到的一种方法是定义不同的TState 类型,如下所示:
class Trace
{
public string Message {get;set;};
public IDictionary<string, string> Properties;
public Trace(string message, IDictionary<string, string> properties)
{
this.Message = message;
this.Properties = properties;
}
}
然后当我需要跟踪时,我会执行以下操作:
logger.Log<Trace>(LogLevel.Information, eventId, new Trace("sample trace",null));
通过这种方式,我根据TSTate 的类型(我为异常、度量和事件创建类型)切换了我在Log<TState> 实现中使用的trackXXX 方法。但这看起来太复杂了,无法编写简单的跟踪,我还缺少其他方法吗?
【问题讨论】:
-
问题是 - 为什么你需要使用 ILogger 界面?用例是什么?
-
用例是在 dot net core 中,它是一等公民,因为它是自动注入的(如果我实现了提供程序、工厂等),并且会自行记录内部 dot net core 跟踪。此外,我想记录到多个地方,如事件日志、本地文件和应用程序洞察,这更容易(因为有现有的提供程序用于这些目的,我可以添加和使用,而不是自己编写所有这些)跨度>
-
嗨@AzureMinotaur,您找到解决方案了吗?
标签: c# logging .net-core azure-application-insights