【问题标题】:How to use Microsoft.Extensions.Logging with Application Insights to log events and metrics如何使用 Microsoft.Extensions.Logging 和 Application Insights 来记录事件和指标
【发布时间】: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&lt;TState&gt; 实现中使用的trackXXX 方法。但这看起来太复杂了,无法编写简单的跟踪,我还缺少其他方法吗?

【问题讨论】:

  • 问题是 - 为什么你需要使用 ILogger 界面?用例是什么?
  • 用例是在 dot net core 中,它是一等公民,因为它是自动注入的(如果我实现了提供程序、工厂等),并且会自行记录内部 dot net core 跟踪。此外,我想记录到多个地方,如事件日志、本地文件和应用程序洞察,这更容易(因为有现有的提供程序用于这些目的,我可以添加和使用,而不是自己编写所有这些)跨度>
  • 嗨@AzureMinotaur,您找到解决方案了吗?

标签: c# logging .net-core azure-application-insights


【解决方案1】:

当您使用 Application Insights SDK for ASP.NET Core 并启用 Application Insights 时,将创建内部 ILogger 实现。你可以看到here 它是如何工作的。

所以要回答您的问题,如果您使用的是面向 ASP.NET Core 的 AI SDK,则不需要实现自己的 ILogger。但是,如果必须,您可以使用链接的实现作为示例。

【讨论】:

  • 很高兴知道有一个简单的默认实现仅用于跟踪,但它不允许我跟踪自定义事件或指标。我想使用 dotnet 核心“本机”支持的 ILogger 接口来实现一个 App 洞察记录器,该记录器也可以编写自定义事件和指标(不仅仅是跟踪)。不幸的是,链接的示例没有为此提供任何指导。
【解决方案2】:

以下是 App Insights 的 ILogger 实现:https://github.com/Azure/azure-webjobs-sdk/blob/5140983cb163b20bf6af60afccebb705bc80ad80/src/Microsoft.Azure.WebJobs.Logging.ApplicationInsights/ApplicationInsightsLogger.cs

您可以做大致相同的事情,包装 TelemetryClient,但添加对事件和其他东西(如 TrackDependency)的支持,它们将从以下位置调用:

Log(LogLevel logLevel, EventId eventId, TState state, Exception异常, Func formatter)

基于 EventId 的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 1970-01-01
    相关资源
    最近更新 更多