ASP.NET Core 8 OpenTelemetry

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

我的 ASP.NET Core 8 代码中有以下 OpenTelemetry 配置(它将日志和指标推送到 Azure 上的 Application Insights):

builder.Services
       .AddOpenTelemetry()
       .UseAzureMonitor(x => x.ConnectionString = configuration.AppIns.ConnStr)
       .ConfigureResource(builder =>
            {
                builder.Clear();
                builder
                    .AddService(serviceName: "MyService1", serviceInstanceId: Environment.MachineName);
            })
       .WithMetrics(builder => {})
       .WithTracing();

在我的课堂上,我使用这样的日志:

public class MyClass1
{
    private readonly ILogger<MyClass1> _logger;

    public MyClass1(ILogger<MyClass1> logger)
    {
        // ...

        void Method() 
        {
            _logger.LogInformation("test1");
            // ...
        }
    }
}

问题是在日志中我看不到类名(带有命名空间),也看不到记录日志的文件路径。换句话说,如何在 Application Insights CustomDimensions 中看到

MyClass1

.net asp.net-core open-telemetry
1个回答
0
投票

您可以按照简单的步骤

  1. 使用
    logger.BeginScope()
    实现中间件来获取机器名称或任何您需要的内容..
  2. 您可以在 AppLogger 包装器中实现 filepath 和 calssNames 或任何您需要的内容
  3. 根据需要使用带有消息的日志

中间件示例代码:

public class LoggingMiddleware
{
    private readonly RequestDelegate _next;

    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context, ILogger<LoggingMiddleware> logger)
    {
        using (logger.BeginScope(new Dictionary<string, object> { ["MachineName"] = Environment.MachineName }))
        {
            await _next(context);
        }
    }
}

// In Startup.cs or Program.cs, depending on your project's setup
app.UseMiddleware<LoggingMiddleware>();

自定义应用程序记录器:

public class AppLogger<T>
{
    private readonly ILogger<T> _logger;

    public AppLogger(ILogger<T> logger)
    {
        _logger = logger;
    }

    public void LogInformation(string message, [CallerFilePath] string filePath = "")
    {
        _logger.LogInformation($"{typeof(T).FullName} [{filePath}]: {message}");
    }

    // Implement other logging methods (LogDebug, LogError, etc.) as needed
}

您的应用程序中的用法示例:

public class MyClass
{
    private readonly AppLogger<MyClass> _logger;

    public MyClass(AppLogger<MyClass> logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        _logger.LogInformation("Doing something important.");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.