Exception 的应用程序洞察和自定义属性

Application insights and custom properties of Exception

我有以下异常:

public class InvalidStatusCodeException : Exception
{
    public HttpStatusCode ReceivedStatusCode { get; set; }
    public string ApiUrl { get; set; }

    public InvalidStatusCodeException(HttpStatusCode receivedStatusCode, string apiUrl)
    {
        ReceivedStatusCode = receivedStatusCode;
        ApiUrl = apiUrl;
    }
}

在某些情况下抛出它:

        string url = "api/group/1/getAll";
        var response = await _client.GetAsync(url);
        if (!response.IsSuccessStatusCode)
            throw new InvalidStatusCodeException(response.StatusCode, url);

如果我捕获并记录此异常:

        catch(InvalidStatusCodeException status_ex)
        {
            string error = $"Invalid Status code for request: '{status_ex.ApiUrl}', received code: {status_ex.ReceivedStatusCode}";
            log.LogError(status_ex, error, "InvalidStatusCode");
        }

我没有看到我的自定义属性(ReceivedStatusCode、ApiUrl)的值,只能在错误消息中看到详细信息。

如果我根本没有捕捉到这个异常,并且异常被自动记录下来,那么根本无法查看详细信息。

有什么方法可以在不额外捕获异常的情况下查看这些自定义属性?

向基地添加消息Exception

public class InvalidStatusCodeException : Exception
{
    public HttpStatusCode ReceivedStatusCode { get; set; }
    public string ApiUrl { get; set; }

    public InvalidStatusCodeException(HttpStatusCode receivedStatusCode, string apiUrl) 
        : base($"Invalid Status code for request: '{apiUrl}', received code: {receivedStatusCode}")
    {
        ReceivedStatusCode = receivedStatusCode;
        ApiUrl = apiUrl;
    }
}

您可以使用结构日志记录的概念,将命名常量记录为自定义属性。

catch(InvalidStatusCodeException status_ex)
{
     log.LogError(status_ex, "Invalid Status code for request: '{ApiUrl}', received code: {ReceivedStatusCode}", status_ex.ApiUrl, status_ex.ReceivedStatusCode);
 }

以上日志将在应用程序洞察日志中添加 ApiUrlReceivedStatusCode 作为自定义属性。

更新

你不会抛出并捕获异常。您可以登录 if (!response.IsSuccessStatusCode) 的 else 块,如下所示:

 if (!response.IsSuccessStatusCode)
 {
     throw new InvalidStatusCodeException(response.StatusCode, url);
 }
 else
 {
     log.LogError(status_ex, "Invalid Status code for request: '{ApiUrl}', received code: {ReceivedStatusCode}",
         status_ex.ApiUrl, status_ex.ReceivedStatusCode);
 }

记录自定义属性的其他方式是通过记录范围(检查 this) and via TelemetryInitializer (check this