You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中从Application Insight获取日志数据?

How to Retrieve Application Insights Log Data in C#

Got it, let's walk through practical ways to pull log data from Application Insights in C#—this is exactly what I used when building custom dashboards, so here's the step-by-step breakdown:

Prerequisites

First, set up your project with the necessary tools:

  • Install the latest NuGet packages:
    Install-Package Azure.Monitor.Query
    Install-Package Azure.Identity
    
  • Grab your Application Insights connection string or resource ID from the Azure portal (found in the Overview tab of your AI resource).
  • Ensure your authentication principal (local dev account, Managed Identity, or Service Principal) has Reader or Monitoring Reader permissions on the Application Insights resource.

This is the modern, supported SDK from Microsoft for querying Azure Monitor data (including Application Insights logs). Here's a complete code example:

using Azure.Monitor.Query;
using Azure.Identity;
using System;
using System.Threading.Tasks;

namespace AiLogRetriever
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Replace with your Application Insights connection string
            string aiConnectionString = "InstrumentationKey=YOUR_KEY;IngestionEndpoint=https://YOUR_REGION.in.applicationinsights.azure.com/;LiveEndpoint=https://YOUR_REGION.livediagnostics.monitor.azure.com/";
            
            // Initialize client with default auth (works for local dev & production)
            var logsClient = new LogsQueryClient(new DefaultAzureCredential());

            // Define your Kusto query—customize this to fetch the logs you need
            // Example: Get last 24 hours of trace logs, sorted by newest first
            string kustoQuery = @"
                traces
                | where timestamp > ago(24h)
                | where severityLevel >= 2 // Filter for warnings and errors (adjust as needed)
                | order by timestamp desc
                | take 100 // Limit results for testing
            ";

            try
            {
                // Execute the query
                var queryResponse = await logsClient.QueryAsync(
                    new Uri($"https://api.applicationinsights.io/v1/apps/YOUR_APP_ID/query"),
                    kustoQuery,
                    new TimeSpan(0, 5, 0) // 5-minute timeout
                );

                // Process and print results
                foreach (var row in queryResponse.Value.Table.Rows)
                {
                    Console.WriteLine($"[{row["timestamp"]}] {row["severityLevel"]}: {row["message"]}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to fetch logs: {ex.Message}");
            }
        }
    }
}

Key Details to Note

  • Kusto Query Language: Application Insights stores logs in a Kusto database, so you'll use Kusto syntax to filter, sort, and aggregate data. Common tables you might query include:
    • traces: Application trace logs
    • requests: HTTP request logs
    • exceptions: Unhandled exception logs
    • customEvents: Custom events you've tracked
  • Authentication: DefaultAzureCredential automatically handles authentication across environments:
    • Local development: Uses your Azure CLI, Visual Studio, or Azure AD account
    • Production: Uses Managed Identity (if running on Azure services like App Service) or Service Principal
  • Rate Limits: Azure enforces query rate limits to prevent abuse. If you're pulling large datasets, consider caching results or batching queries.

Example Advanced Query

If you need aggregated data for your dashboard (like daily error counts), adjust the Kusto query:

requests
| where timestamp > ago(7d)
| where resultCode startswith "5" // Filter 5xx errors
| summarize ErrorCount = count() by bin(timestamp, 1d), name
| order by timestamp asc

Once you've got this working, you can shape the query results into the format your custom dashboard needs. Feel free to tweak the queries or auth setup based on your specific environment!

内容的提问来源于stack exchange,提问作者lokanath das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:49:57