Azure App Insights 记录到 .Net 核心中的异常和跟踪

Azure App Insights logging to both Exceptions and Traces in .Net core

我正在寻找一种登录跟踪和异常的方法。如果我登录两者并且看起来每个人都喜欢它,似乎更容易跟踪。除非有理由不这样做。

Logger.LogWarning(ex, "Audit failed");
Logger.LogWarning("Audit failed");

第一个记录异常,第二个记录跟踪。我必须像这样将它添加到很多地方才能将其登录到两者中。 还有其他我错过的方式吗?

如果我们想将日志同时发送到tracesexceptions,我们通常使用2种Logger.LogWarning()方法。

没有直接的方法可以做到这一点。你可以考虑写一个extension method,其中包含2个方法Logger.LogWarning(ex, "Audit failed"); Logger.LogWarning("Audit failed");。然后您只能调用此扩展方法一次并将日志发送到 tracesexceptionsExtension methods 如下所示:

public static class MyCustomLogger
{

    //define an extension method.
    public static void Custom_LogWarning(this ILogger logger, string msg)
    {
        //send this log into traces table
        logger.LogWarning(msg);

        //send this log into exceptions table
        logger.LogWarning(new Exception(), msg);
    }
}

然后你可以像下面这样使用这个扩展方法:

logger.Custom_LogWarning("it is a message from my custom log method...");