gpt4 book ai didi

c# - 如何在控制台应用程序中配置 ConsoleLogger?

转载 作者:行者123 更新时间:2023-12-04 13:39:33 24 4
gpt4 key购买 nike

我正在尝试使用 .NET CORE 3.1 构建控制台应用程序,但在注入(inject)控制台记录器时遇到问题。

在最近的版本中,日志记录的注入(inject)方式似乎发生了重大变化,并且各种风格的教学教程似乎都与我正在尝试做的事情不符。

我有一个界面:

public interface IMyDoer
{
void DoSomething();
}

还有一个我想注入(inject) ILogger 的类:
public class MyDoer : IMyDoer
{
private readonly ILogger logger;
public MyDoer(ILogger logger)
{
this.logger = logger;
}

public void DoSomething()
{
this.logger.Log(LogLevel.Information, "Doing something");
}
}

然后我有我的 Main(),我试图配置一个 DI 容器来构造一个 Doer 对象,配置 ILogger 以登录到控制台。
public class Program
{
public static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);

var serviceProvider serviceCollection.BuildServiceProvider();

var myDoer = serviceProvider.GetService<IMyDoer>();

myDoer.DoSomething();
}

private static void ConfigureServices(ServiceCollection serviceCollection)
{
serviceCollection.AddLogging(configure => {
configure.AddConsole();
});

serviceCollection.AddSingleton<IMyDoer, MyDoer>();
}
}

作为替代方案,我尝试过:
public class Program
{
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);

using (var serviceProvider = serviceCollection.BuildServiceProvider())
using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole()))
{
var myDoer = serviceProvider.GetService<IMyDoer>();

myDoer.DoSomething();
}
}

private static void ConfigureServices(ServiceCollection serviceCollection)
{
serviceCollection
.AddSingleton<IMyDoer, MyDoer>();
}
}

在任何一种情况下,我都会得到一个异常(exception):
System.InvalidOperationException
HResult=0x80131509
Message=Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyDoer.DoSomething'.
Source=Microsoft.Extensions.DependencyInjection

关于我应该如何做的任何想法?

最佳答案

ILogger未在 ASP.NET Core DI 容器中注册。相反,使用 ILogger<T> :

public class MyDoer : IMyDoer
{
private readonly ILogger<MyDoer> logger;

public MyDoer(ILogger<MyDoer> logger)
{
this.logger = logger;
}

// ...
}
ILogger<T>使用类型名称 ( YourNamespace.MyDoer ) 作为 log category :

That category is included with each log message created by that instance of ILogger.



设置您自己的日志类别并创建 ILogger 的实现自己,使用 ILoggerFactory :
public class MyDoer : IMyDoer
{
private readonly ILogger logger;

public MyDoer(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger("YourCategory");
}

// ...
}

关于c# - 如何在控制台应用程序中配置 ConsoleLogger?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59493726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com