简体   繁体   中英

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 . 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.

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.

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.

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