[英].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? 是否可以使用.NET Core 2.1的类库中的配置项登录数据库?
I managed to build a working version for .NET MVC 5 using NLog. 我设法使用NLog为.NET MVC 5构建了一个工作版本。 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.
但是,当涉及到.NET Core 2.1时,就依赖于在Startup.cs和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 这是我展示Ncode ASP.NET Core 2.1使用Nlog配置作为.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. 尤其是在类库中,应该使用日志记录外观,例如Microsoft.Extensions.Logging,而不是具体的日志记录提供程序(例如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. 然后,在类内部,使用设置为
_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.
这样,每个单独的应用程序都控制自己的日志记录提供程序,而您的类库类仅使用抽象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.