Use ASP.NET Core logging without using WebHost

2019-07-31 05:25发布

We have .NET Core applications that could benefit from ASP.NET Core logging (and service provider) but they're not using any WebHost or WebHostBuilder.

I'd like to peek inside extensions/methods like ConfigureLogging or UseStartup to get some inspiration on how to set-up my root configuration/service provider.

I thought ASP.NET Core was open-source, but somehow I lack the talent to find those sources. Where can I learn more about how all this is set up, and how I could use them in any console app, not just apps using WebHostBuilder?

2条回答
不美不萌又怎样
2楼-- · 2019-07-31 06:15

The various components from ASP.NET Core are all usable separately. So you can absolutely use things like Microsoft.Extensions.Logging, or even other things like DependencyInjection, Configuration or Options separately without having to actually use ASP.NET Core or its WebHost.

I could point you to various locations in the sources now (e.g. the WebHostBuilder, the WebHost, or the default builder), but getting logging up and running in your own application is actually pretty simple, so you don’t need to browse through all that.

Instead, just add a reference to Microsoft.Extensions.Logging and your favorite logging providers, e.g. Microsoft.Extensions.Logging.Console, and then set up a logger factory and create a logger:

var loggerFactory = new LoggerFactory();
loggerFactory.AddConsole();

var logger = loggerFactory.CreateLogger("categoryName");
logger.LogInformation("Whee!");

That is all you need to get logging working. Of course, you now need to create your own loggers and pass it to where you need it, but you have full control over it.

If you like, you can also add dependency injection to the mix by adding a reference to Microsoft.Extensions.DependencyInjection and creating a service collection:

var services = new ServiceCollection();

// add logging
services.AddLogging(loggerBuilder =>
{
    loggerBuilder.AddConsole();
});

// add your services
services.AddTransient<MyService>();


// create the service provider
var serviceProvider = services.BuildServiceProvider();

// request your service and do something
var service = serviceProvider.GetService<MyService>();
service.DoSomething();
public class MyService
{
    private readonly ILogger<MyService> _logger;
    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        _logger.LogInformation("Did something!");
    }
}

And suddenly you have working dependency injection with logging in just a few lines. So you can set up your own environment for console applications, and then built upon those techniques for your application—without relying on actual ASP.NET Core stuff.

查看更多
爷、活的狠高调
3楼-- · 2019-07-31 06:17

It is worth mentioning that since .NET Core 2.1, you can now use a HostBuilder for such projects. Works very well.

查看更多
登录 后发表回答