c# - 具有无效检测 key 的 Application Insights - 如何在未抛出错误时进行处理

标签 c# azure-application-insights

如果在将消息跟踪到 Application Insights 时使用了无效的检测 key ,是否可以捕获错误?

我正在以编程方式指定如下所示的检测 key ,但没有引发异常。
我正在尝试构建一个 Logging WebApi,它将根据消息是否成功记录到 Application Insights 来返回成功或失败?

TelemetryConfiguration config = TelemetryConfiguration.CreateDefault();
config.InstrumentationKey = "ABC";
client.TrackTrace("Test"),SeverityLevel.Information);

最佳答案

您应该实现您自己的 channel 来实现 ITelemetryChannel ,并根据需要处理异常。

这是一个简单的例子:

public class SynchronousTelemetryChannel : ITelemetryChannel
{
    private const string ContentType = "application/x-json-stream";
    private readonly List<ITelemetry> _items;
    private object _lock = new object();
    public bool? DeveloperMode { get; set; }
    public string EndpointAddress { get; set; }

    public SynchronousTelemetryChannel()
    {
        _items = new List<ITelemetry>();
        EndpointAddress = "https://dc.services.visualstudio.com/v2/track";
    }

    public void Send(ITelemetry item)
    {
        lock (_lock)
        {
            _items.Add(item);
        }
    }

    public void Flush()
    {
        lock (_lock)
        {
            try
            {
                byte[] data = JsonSerializer.Serialize(_items);
                new Transmission(new Uri(EndpointAddress), data, ContentType, JsonSerializer.CompressionType).SendAsync().Wait();
                _items.Clear();
            }
            catch (Exception e)
            {
                // Do whatever you want.
            }
        }
    }

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
}

然后,通过代码或 configuration file 使用您的 channel 初始化配置:

        TelemetryConfiguration.Active.TelemetryChannel = new SynchronousTelemetryChannel();

关于c# - 具有无效检测 key 的 Application Insights - 如何在未抛出错误时进行处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40217337/

相关文章:

c# - Azure Functions - 给定的程序集名称或代码库无效。 (HRESULT : 0x80131047) 的异常

azure - 如何在 API 策略中的应用程序见解请求中包含自定义字段

azure - 无论如何,要查看 Application Insight SDK 上传到 azure 的内容吗?

c# - 在方法内部等待,直到事件被捕获

azure-application-insights - 由于权限不足,应用程序洞察监视器不会将数据发送到门户

azure - 如何根据自定义图表中的azure仪表板中的选定时间段计算时间粒度

azure - 如何在 App Insights 中保存共享查询

c# - .Net Core 3.1 使用 MySql 向现有项目添加身份

c# - 如何从 C# 代码将默认打印 'zoom > scale to paper size' 设置为 A4?

c# - WeakEventManager 和静态事件