Reputation: 17677
We have a plugin that gets distributed with third party software (also with our own software) Our plugin is written in C# and contains some log4net logging. In our own software, we have a .exe.config that contains our log4net section and allows for configuration. However on the third-party side we are unable to do this.
Any suggestions on how I can configure it from within the code? (Assuming it has not already been configured, in the case of our own software)?
Upvotes: 6
Views: 7644
Reputation: 3393
While I agree with Mauricio Scheffer's answer in general, there may be cases where the DLL needs to log before the main application. In my case, I implemented a SOAP extension class in a DLL to log SOAP requests and responses for any ASMX web service. Because the soap extension is in a DLL which is executed before the web method execution, log4net must be configured programmatically in the DLL. But each web service contains its own log4net.config file which the DLL needs to locate and load to configure log4net programmatically.
My solution was to add a method to determine to location of 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);
}
Upvotes: 1
Reputation: 4034
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 config file
such as
<log4net>
<appender>
</appender>
<logger >
</logger>
</log4net>
Upvotes: 1
Reputation: 99730
It's possible to do it, but IMHO it's not a good idea. It's the application, not the libraries, that decides if/how/when/where/what to log. Libraries should only offer logging support (you already do this).
Upvotes: 10
Reputation: 5914
The log4net environment is fully configurable programmatically.
Upvotes: 4