Mik*_*oud 3 .net logging dependency-injection .net-core
我有一个 .NET Core 控制台应用程序。很简单。在这一点上,目标只是让 DI 和配置集成。但是,LogDebug没有登录到控制台。
我在这里可能做错了什么?
class Program
{
static void Main(string[] args)
{
var topic = Environment.GetEnvironmentVariable("RECEIVER_TOPIC");
var entity = Environment.GetEnvironmentVariable("RECEIVER_ENTITY");
//setup our DI
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
//configure console logging
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug);
var logger = serviceProvider
.GetService<ILoggerFactory>()
.CreateLogger<Program>();
logger.LogDebug($"Starting application. Topic: {topic}. Entity: {entity}.");
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
static IConfigurationRoot GetConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
return builder.Build();
}
}
Run Code Online (Sandbox Code Playgroud)
我添加了Microsoft.Extensions.Logging.DebugNuGet 包,并修改了serviceProvider初始化以附加AddDebug如下内容:
serviceProvider
.GetService<ILoggerFactory>()
.AddConsole(LogLevel.Debug)
.AddDebug();
Run Code Online (Sandbox Code Playgroud)
但它甚至没有记录到Debug窗口。
得到它的工作。我认为关键是我还不清楚需要注册混凝土,因为我认为扩展是注册混凝土。
class Program
{
static void Main(string[] args)
{
var topic = Environment.GetEnvironmentVariable("RECEIVER_TOPIC");
var entity = Environment.GetEnvironmentVariable("RECEIVER_ENTITY");
// Create service collection
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// Create service provider
var serviceProvider = serviceCollection.BuildServiceProvider();
var logger = serviceProvider
.GetRequiredService<ILoggerFactory>()
.CreateLogger<Program>();
logger.LogDebug($"Starting application. Topic: {topic}. Entity: {entity}.");
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
static void ConfigureServices(IServiceCollection serviceCollection)
{
// Add logging
serviceCollection.AddSingleton<ILoggerFactory, LoggerFactory>();
serviceCollection.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
serviceCollection.AddLogging(loggingBuilder => loggingBuilder
.AddConsole()
.AddDebug()
.SetMinimumLevel(LogLevel.Debug));
// Build configuration
var configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", false)
.Build();
// Add access to generic IConfigurationRoot
serviceCollection.AddSingleton(configuration);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4645 次 |
| 最近记录: |