简体   繁体   English

如何在.Net Core 中使用不同的第三方记录器登录到文件? 第三方记录器可能会在应用程序启动时动态更改

[英]How to log to a file using different third party logger in .Net Core? Third party logger may change dynamically when application starts

Developing simple application which uses Microsoft.Extensions.Logging framework to log information to file by using Log4Net or NLog or SeriLog .开发使用Microsoft.Extensions.Logging框架的简单应用程序,使用Log4NetNLogSeriLog将信息记录到文件中。 For that using below simple code and its working fine.为此,使用下面的简单代码及其工作正常。

var factory = new LoggerFactory().AddLog4Net();
//var factory = new LoggerFactory().AddNLog();
//var factory = new LoggerFactory().AddSerilog();
ILogger logger = factory.CreateLogger<Program>();
logger.Log(LogLevel.Debug, "Some message to log");

For the above sample to work i need to add NLog.Extensions.Logging or Serialog.Extensions.Logging or Microsoft.Extensions.Logging.Log4Net.AspNetCore in my sample application.要使上述示例正常工作,我需要在示例应用程序中添加NLog.Extensions.LoggingSerialog.Extensions.LoggingMicrosoft.Extensions.Logging.Log4Net.AspNetCore

What my question is, need to build my sample application generically without referring above Nuget packages and based on customer desire they can use or configure NLog or SeriLog third parties to log, it will be decided by some configure file during runtime.我的问题是,需要在不参考上述 Nuget 包的情况下通用地构建我的示例应用程序,并且根据客户的需求,他们可以使用或配置 NLog 或 SeriLog 第三方进行日志记录,这将由运行时的一些配置文件决定。

Without compiling my application again, i need to allow customer to use required third party frameworks.无需再次编译我的应用程序,我需要允许客户使用所需的第三方框架。 My application should read from config file and write log to file by using corresponding frameworks that mentioned in config file.我的应用程序应该使用配置文件中提到的相应框架从配置文件中读取并将日志写入文件。

Hope you can understand my requirement clearly, thanks in advance.希望您能清楚地理解我的要求,在此先感谢。

In this case, the logging is not an "external tool", it is a part of the application.在这种情况下,日志记录不是“外部工具”,它是应用程序的一部分。 That's why you can't implement a "generic" logging, you have to have it compiled into your app.这就是为什么您不能实现“通用”日志记录的原因,您必须将其编译到您的应用程序中。 But you are not limited to only one.但你不仅限于一个。 You could compile in all three of them, and during the startup initialize the one you need based on the configuration您可以编译所有三个,并在启动期间根据配置初始化您需要的一个

var factory = Configuration["LoggingSystem"] switch
{
    "log4net" => loggerFactory.AddLog4Net(),
    "nlog" => loggerFactory.AddNLog(),
    ...
    _ => throw new Exception()
};

Of course that means your app should reference all the nugets, but that shouldn't be a problem.当然,这意味着您的应用程序应该引用所有的 nuget,但这应该不是问题。

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

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