Log4Net configuration in dll plugin?

We have a plugin that is distributed with third-party software (also with our own software). Our plugin is written in C # and contains some log4net logs. In our own software, we have a .exe.config that contains our log4net section and allows for customization. However, on the side of a third party, we cannot do this.

Any suggestions on how I can configure it from code? (Assuming it has not been configured yet, in the case of our own software)?

+6
source share
4 answers

This can be done, but IMHO this is not a good idea. This is an application, not a library, that decides if / how / when / where / what needs to be registered. Libraries should only offer journaling support (you already do this).

+10
source

use

private static void LoadLoggerConfig(string filename) { FileInfo file = new FileInfo(filename); if (!file.Exists) { throw new FileLoadException(string.Format("The configuration file {1} for the logger cannot be found in {0}", file.Directory.FullName, LOG4NET_CONFIG_FILE), LOG4NET_CONFIG_FILE); } log4net.Config.XmlConfigurator.Configure(file); } 

and create an external log4net configuration file

such as

 <log4net> <appender> </appender> <logger > </logger> </log4net> 
+1
source

While I agree with the Mauricio Scheffer answer in general, there may be times when a DLL needs to register before the main application. In my case, I have implemented a SOAP extension class in a DLL to register SOAP requests and responses for any ASMX web service. Because the soap extension is in the DLL, which is executed before the web method is executed, log4net must be programmed in the DLL programmatically. But each web service contains its own log4net.config file, which the DLL needs to find and load in order to program log4net programmatically.

My solution was to add a method to locate the running DLL

 static public string AssemblyDirectory { get { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } } 

and then in the constructor of my DLL to load the configuration programmatically

 if (!log4net.LogManager.GetRepository().Configured) { // assume that log4net.config is located in the root web service folder var configFileDirectory = (new DirectoryInfo(TraceExtension.AssemblyDirectory)).Parent; var configFile = new FileInfo(configFileDirectory.FullName + "\\log4net.config"); if (!configFile.Exists) { throw new FileLoadException(String.Format("The configuration file {0} does not exist", configFile)); } log4net.Config.XmlConfigurator.Configure(configFile); } 
+1
source

Source: https://habr.com/ru/post/888462/


All Articles