I have been working on getting log4net working in a demo program for a client so they can integrate it with their code base. I found this article when doing the implementation http://www.codeproject.com/Articles/14819/How-to-use-log4net , and one of the steps described is
Step 2: Add below line in your AssemblyInfo.cs file.
[assembly: log4net.Config.XmlConfigurator(ConfigFile="Web.config", Watch=true)] //For log4net 1.2.10.0
and as soon as I added that line of code to my AssemblyInfo.cs the logger started working.
I did some Googling around the place to try to understand why this line is required, and most documentation and comments claimed AssemblyInfo is for optional configuration information. I don't understand why adding this line would have made my program work; my key questions are - how does the configuration information in AssemblyInfo.cs get picked up and used (and is there some documentation that describes this clearly) - how did log4net "know" to pick up that information from AssemblyInfo.cs?
I understand from What does the assembly keyword mean in the AssemblyInfo.cs. Does it permit to use method inside? that these are attributes on the assembly but not the mechanism behind it.
Nice topic. I cannot provide a link, as you are asking, only few points, findings. Some of my statements could be known and obvious. I am trying to put them together here, in one place. And give the answer how that magic with log4Net setting is triggered.
Given this, what we can do with attributes. Our (custom) code is allowed to use reflection to check if there is an Attribute, mostly of a specific known type (eg XmlConfiguratorAttribute ). If such Attribute exists, we can "execute" it. For example. I am using ASP.NET MVC having its "runtime" which grants that any Attribute of a type IFilter will be executed properly. It is the MVC runtime, observing classes and methods and explicitly executing these Attributes.
The solely stated attribute declaration inside of the AssemblyInfo.cs is not enough. As in the snippet above where XmlConfiguration is declared. Usally there will be some other call (in ASP.NET maybe in Global.asax) constructing the ILog
ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
Well, and somewhere in the flow of methods call-chain, inside of the Log4Net will be a check if exists:
var attributes = Attribute.GetCustomAttributes(thisAssembly, typeof(XmlConfiguratorAttribute));
and if yes (assembly has such attribute) - log4Net can use it, force it to do its job (eg configure itself from xml)
Log4net has code that looks for an assembly-level XmlConfigurator
attribute in the calling assembly.
It reads the properties of the attribute that it finds and configures itself appropriately.
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.