我的 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
。
从版本
1.4.0-beta.1
开始,可以记录引发异常的类名或使用遥测导出器创建日志。
添加到您的
csproj
:
<PackageReference Include="Azure.Monitor.OpenTelemetry.Exporter" Version="1.4.0-beta.1" />
此功能正式版发布前,请在您的应用程序中调用:
AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true);
跟踪应该或多或少像这样配置:
.WithTracing(cfg => { cfg
.AddAspNetCoreInstrumentation(opt => opt.RecordException = true)
.AddSource("Azure.*")
.AddAzureMonitorTraceExporter(opt => opt.ConnectionString = azureMonitorConnectionString);
});
因此,您将在 App Insights 中的
CategoryName
下看到 CustomDimensions
字段。该字段将包含生成日志的类的名称。
您可以按照简单的步骤
logger.BeginScope()
实现中间件来获取机器名称或任何您需要的内容..中间件示例代码:
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.");
}
}