2

I have custom xml file with the log4net configurations. Below code is used for configuring the log4net. It is working fine.

The question is how does LogManager.Getlogger gets the "MyLogger" when it doesnt know the config file details?

Should we maintain any sequence while calling LogManager.GetLogger and xmlconfigurator.configure ?

Class LoggerClass
{

private static readonly ILog fileLogger = LogManager.GetLogger("MyLogger");


public LoggerClass()
{

FileInfo logConfiguration = new FileInfo("ConfigFile.xml");

//Loading the configuration from the xml file. 
XmlConfigurator.Configure(logConfiguration);

}

public void Log(string msg)
{
fileLogger.Log(......); 
}

}
Imortal
  • 31
  • 1
  • 3

2 Answers2

3

LogManager class has static methods that are used by a client to request a logger instance. The GetLogger method is used to retrieve a logger.

The GetLogger method return the object of type ILog which contains methods for logging at different levels and also has properties for determining if those logging levels are enabled in the current configuration.

And about the sequence, the invocation of the Xmlconfigurator.Configure() method sets up the logging functionality, hence before writing any log, the log4net library must be set up using this command Xmlconfigurator.Configure().

And the sequence of calling LogManager.GetLogger() and Xmlconfigurator.Configure() does not matter. Just make sure that before any logging, you have initialized the logger using LogManager.GetLogger() method and have set up the logger using Xmlconfigurator.Configure().

Reference: log4net documentaion

I hope, this helps and answers your question :)

AbdulRahman Ansari
  • 3,007
  • 1
  • 21
  • 29
  • Is the BasicConfigurator.Configure() required? right now i dont use this. just with GetLogger() and XmlConfigurator.Configure() it is working fine? – Imortal Jul 01 '14 at 09:40
  • @Imortal Sorry my mistake, check updated answer. If you want to configure without XML file then you can use `BasicConfigurator.Configure()`. If you are using `XmlConfigurator.Configure()` then `BasicConfigurator.Configure()` is not required. – AbdulRahman Ansari Jul 01 '14 at 09:45
0

Usually XmlConfigurator.configure() is done at application start in global.asax in ASP.NET application, so that all classes in application get log4net configurations.

//Global.asax

void Application_Start(object sender, EventArgs e)
{
    log4net.Config.XmlConfigurator.Configure();
}
Vaibhav Vidhate
  • 186
  • 1
  • 5