简体   繁体   English

如何使用LoggerFactory和Microsoft.Extensions.Logging进行.NET Core Console使用C#进行日志记录

[英]How to Use LoggerFactory and Microsoft.Extensions.Logging for .NET Core Console Logging With C#

I've created a console application that uses a service layer. 我创建了一个使用服务层的控制台应用程序。

Program.cs Program.cs中

public static void Main(string[] args)
{
    // Create service collection
    var serviceCollection = new ServiceCollection();
    ConfigureServices(serviceCollection);

    // Create service provider
    var serviceProvider = serviceCollection.BuildServiceProvider();

    // Entry to run app
    serviceProvider.GetService<App>().Run().RunSynchronously();
}

private static void ConfigureServices(IServiceCollection serviceCollection)
{
    // Configuration
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", false)
        .Build();

    serviceCollection.AddOptions();
    serviceCollection.Configure<Settings>(options =>
    {
        //...
    });

    // Services
    serviceCollection.AddTransient<IOneService, OneService>();
    serviceCollection.AddTransient<ISecondService, SecondService>();

    // Repositories
    serviceCollection.AddTransient<MyContext, MyContext>();
    serviceCollection.AddTransient<IOneRepository, OneRepository>();

    // App
    serviceCollection.AddTransient<App>();

    // Logger

    // Automapper
    serviceCollection.AddSingleton(new AutoMapperProfileConfiguration());
    serviceCollection.AddScoped<IMapper>(sp =>
        new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));
}

I'm getting this error System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger 1` and I'm guessing that i have to setup LoggerFactory and Microsoft.Extensions.Logging for .NET Core Logging, but I can't get it right. 我收到此错误System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger 1`的服务,我猜我必须为.NET Core Logging设置LoggerFactory和Microsoft.Extensions.Logging,但是我做不到。

I've tried something like this in Main(): 我在Main()中尝试过类似的东西:

// Attempt 1
ILoggerFactory loggerFactory = new LoggerFactory()
    .AddConsole()
    .AddDebug();
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation(
  "This is a test of the emergency broadcast system.");

// Attempt 2
serviceCollection.AddSingleton(new LoggerFactory()
    .AddConsole()
    .AddDebug());

Any ideas? 有任何想法吗?

It should work: 它应该工作:

var serviceProvider = new ServiceCollection()
                      .AddLogging() //<-- You were missing this
                      .BuildServiceProvider();
//get logger
var logger = serviceProvider.GetService<ILoggerFactory>()
            .CreateLogger<Program>();

Packages to install : Microsoft.Extensions.DependencyInjection; 要安装的软件包:Microsoft.Extensions.DependencyInjection; Microsoft.Extensions.Logging; Microsoft.Extensions.Logging;

If you'd like to have Log4Net support for .Net console app like this: 如果你想为.Net控制台应用程序提供Log4Net支持,如下所示:

loggerFactory.AddLog4Net()

you would need to implement ILoggerProvider. 你需要实现ILoggerProvider。 I wrote an article and code how to achieve it: http://www.michalbialecki.com/2018/12/21/adding-a-log4net-provider-in-net-core-console-app/ 我写了一篇文章和代码如何实现它: http//www.michalbialecki.com/2018/12/21/adding-a-log4net-provider-in-net-core-console-app/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 c# 内核 Microsoft.Extensions.Logging 和日志配置 - c# core Microsoft.Extensions.Logging and Log Config 如何在控制台中格式化日志输出?(Microsoft.Extensions.Logging) - How to format the output of logs in the console?(Microsoft.Extensions.Logging) ASP.NET 核心 Web API - 如何解决 Serilog 和 Microsoft.Extensions.Logging 之间的冲突 - ASP.NET Core Web API - How to resolve conflict between Serilog and Microsoft.Extensions.Logging 如何从库代码使用 Microsoft.Extensions.Logging? - How use Microsoft.Extensions.Logging from Library code? C# Microsoft.Extensions.Logging 如何将 output 重定向到特定文件? - C# Microsoft.Extensions.Logging how to redirect output to a specific file? 如何使用 Microsoft.Extensions.Logging 配置和查看日志记录 - How to configure and view logging using Microsoft.Extensions.Logging Microsoft.Extensions.Logging - LogError 未记录异常 - Microsoft.Extensions.Logging - LogError is not logging exception Net Core 3.0 和 Serilog 产生 output 像 Microsoft.Extensions.Logging - Net Core 3.0 and Serilog producing output like Microsoft.Extensions.Logging 如何获取 Microsoft.Extensions.Logging<T> 在使用 Serilog 和 AutoFac 的控制台应用程序中? - How to get Microsoft.Extensions.Logging<T> in console application using Serilog and AutoFac? 如何从Microsoft.Extensions.Logging订阅日志 - How to subscribe to the logs from Microsoft.Extensions.Logging
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM