简体   繁体   中英

.NET Core 2.1 Logging to database from a Class Library

Is it possible to log to a database with items like the configuration sitting in the class library for .NET Core 2.1?

I managed to build a working version for .NET MVC 5 using NLog. However, when it came to .NET Core 2.1, there was a reliance in setting it as a service in Startup.cs and Program.cs.

I actually asked about it in another post but this one is just to get a recommendation for a guide or tutorial to see if its possible?

This is the other post where I showed my code and configuration with NLog ASP.NET Core 2.1 Using Nlog configuration as .NET MVC5

Especially within a class library, you should be using a logging fascade, like Microsoft.Extensions.Logging, rather than a concrete logging provider such as NLog. You then simply inject the logging fascade into your class library classes like:

public class Foo
{
    private readonly ILogger _logger;

    public Foo(ILogger<Foo> logger)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    ...
}

Inside the class, then, you use the injected logging instance set to the _logger ivar. Then, in your actual project that utilizes this class, you set you your logging provider and register the appropriate services. That way, each individual app controls it's own logging providers, and your class library classes just use the abstraction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM