如何在我们的 C# 代码中以编程方式检索 App Insights 请求 ID

问题描述 投票:0回答:1

背景:

我们在 Azure 云服务上托管了一个 Web API,该 API 与 App Insights 集成。当前设置允许在 App Insights 中自动记录对此 Web API 发出的客户端请求。虽然这种自动日志记录功能很有用,但生成的日志无法提供我们操作所需的详细程度。

问题:

主要的挑战是这些自动生成的日志缺少某些对我们的分析至关重要的自定义值。具体来说,在 App Insights 中记录请求后,Web API 中会进行进一步处理。此后续处理与相关 ID (corr id) 相关联。但是,我目前无法在初始 App Insights 日志与 API 中进一步处理期间生成的日志之间建立链接。这种相关性的缺乏阻碍了我们跟踪和分析请求的整个流程的能力。

要求:

  1. 有没有办法通过添加自定义值来增强 App Insights 中自动生成的日志?

  2. 鉴于每个请求都有一个由 App Insights 生成的唯一请求 ID,是否可以在我们的代码中以编程方式检索此请求 ID?这将使我们能够在后续处理阶段记录它,从而实现初始日志和后续日志之间的关联。

关联这些日志的能力对于我们的运营和故障排除工作至关重要。您可以提供任何指导或解决方案来解决此问题,我们将不胜感激。

我无法理解这些请求是如何自动生成的。

azure-application-insights azure-monitor
1个回答
0
投票

使用此参考我可以使用请求 ID 添加日志记录。

Startup.cs

public void ConfigureServices(IServiceCollection services)  
{  
  
    services.AddControllers();  
    services.AddSwaggerGen(c =>  
    {  
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Logs_App_Insights", Version = "v1" });  
    });  
    services.AddApplicationInsightsTelemetry();  
}
 [ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly TelemetryClient _telemetryClient;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, TelemetryClient telemetryClient)
    {
        _logger = logger;
        _telemetryClient = telemetryClient;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var iteration = 1;
        var requestId = HttpContext.TraceIdentifier;
        var operation = _telemetryClient.StartOperation<RequestTelemetry>("WeatherForecastOperation");
        operation.Telemetry.Context.Operation.Id = requestId;

        try
        {
            // Log custom properties
            var customProperties = new Dictionary<string, string>
            {
                { "CustomProperty1", "Value1" },
                { "CustomProperty2", "Value2" }
            };

            _telemetryClient.TrackEvent("CustomEvent", customProperties);

            _logger.LogDebug($"Debug {iteration}");
            _logger.LogInformation($"Information {iteration}");
            _logger.LogWarning($"Warning {iteration}");
            _logger.LogError($"Error {iteration}");
            _logger.LogCritical($"Critical {iteration}");

            // Simulate some processing
            // ...

            // Use the request ID for logging
            LogInformationWithRequestId(requestId, "Log message here.");

            return Ok(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = new Random().Next(-20, 55),
                Summary = Summaries[new Random().Next(Summaries.Length)]
            })
            .ToArray());
        }
        finally
        {
            _telemetryClient.StopOperation(operation);
        }
    }

    private void LogInformationWithRequestId(string requestId, string message)
    {
        // Log information with the request ID
        _logger.LogInformation("[Request ID: {RequestId}] {Message}", requestId, message);

        // Log to the console with the request ID
        Console.WriteLine($"[Request ID: {requestId}] {message}");
    }
}

代码请参阅此git感谢@Jay Krishna Reddy。

输出:

enter image description here

enter image description here 自定义值:

© www.soinside.com 2019 - 2024. All rights reserved.