我的 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
。
您可以按照简单的步骤
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.");
}
}