提问人:Chris Harrington 提问时间:11/17/2023 最后编辑:Amit MohantyChris Harrington 更新时间:11/17/2023 访问量:63
在不同的类中使用依赖注入 (DI) 实现配置的 LoggerFactory
Implementing Configured LoggerFactory with Dependency Injection (DI) in Different Classes
问:
我一直在探索 Microsoft.Extensions.Logging 文档,并找到了使用代码配置 LoggerFactory 的示例。我遇到了这样的模式:
using Microsoft.Extensions.Logging;
using var loggerFactory = LoggerFactory.Create(static builder =>
{
builder
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
.AddConsole();
});
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogDebug("Hello {Target}", "Everyone");
和:
var logger = LoggerFactory.Create(config =>
{
config.AddConsole();
config.AddConfiguration(builder.Configuration.GetSection("Logging"));
}).CreateLogger("Program");
但是,我有兴趣在其他类中使用通过依赖注入 (DI) 配置的它,但我在文档中找不到说明这种方法的示例。loggerFactory
我正在寻求指导或示例来演示如何将配置与 DI 一起使用,从而允许我将 ILogger 实例注入到整个应用程序中的多个类中。关于如何在更广泛的背景下实现这一点的任何见解、代码示例或建议将不胜感激。谢谢!loggerFactory
答:
1赞
Qiang Fu
11/24/2023
#1
您可以创建一个 customloggerfactory 类,并创建一个返回配置的 loggerfactory 的方法。
MyLoggerFactory.cs
public class MyLoggerFactory
{
public ILogger CreateLogger(string categoryName)
{
var loggerFactory = LoggerFactory.Create(static builder =>
{
builder
.AddFilter("Microsoft", LogLevel.Warning)
.AddFilter("System", LogLevel.Warning)
.AddFilter("LoggingConsoleApp.Program", LogLevel.Debug)
.AddConsole();
});
return loggerFactory.CreateLogger(categoryName);
}
}
程序 .cs
builder.Services.AddScoped<MyLoggerFactory>();
然后你可以像这样通过DI使用:
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly ILogger _logger;
public TestController(MyLoggerFactory myLoggerFactory)
{
this._logger = myLoggerFactory.CreateLogger("TestController");
}
[HttpGet("test")]
public void test()
{
_logger.LogInformation("custome logger logged information");
}
}
2赞
Chris Harrington
11/26/2023
#2
这就是我最终所做的——无论如何,现在
程序.cs
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddGoogleCloudConsole(options => {
options.IncludeScopes = true;
options.TraceGoogleCloudProjectId = "saql-cloud-run";
});
var url = $"http://0.0.0.0:{port}";
builder.WebHost.UseUrls(url);
var app = builder.Build();
// logging in out flow
app.Logger.LogInformation($"EnvironmentName: {app.Environment.EnvironmentName}"); // Development
app.MapGet("/", (ILogger<Program> logger) => {
// logging in endpoint
logger.LogInformation("In /");
return Results.Ok("Hello World");
});
我的服务.cs
public class MyService : IMyService
{
private readonly ILogger _logger;
public MyService (ILoggerFactory loggerFactory, IOptions<MySettings> options)
{
_logger = loggerFactory.CreateLogger<MyService>();
}
}
我想我还会尝试 https://stackify.com/net-core-loggerfactory-use-correctly 中所示的“如何从任何地方使用日志记录 API”方法
谢谢大家的建议!
评论
ILogger<T>
builder.Services.AddScoped<ILoggerFactory, LoggerFactory>();