Log4Net的Config配置文件读取

If you've ever seen the web.config file that ASP.NET uses, and thought, "Wow, I'm so glad they configure things that way, in this nice, easy-to-use XML file. Wish I could do that!" then you should check out the System.Configuration namespace. There's an interface called IConfigurationSectionHandler that lets you write your own parsers for your application configuration file, letting you put whatever you want in there.

I've written a bunch of these over the last few months, but today I wrote the last one I ever will. Here's the code for it:

using System;

using System.Configuration ;

using System.Xml ;

using System.Xml.Serialization ;

using System.Xml.XPath ;


namespace DevelopMentor.Candera.Utilities

{

  public class XmlSerializerSectionHandler :
                    
IConfigurationSectionHandler {

    public object Create(

                     object parent,

                     object configContext ,

                     System.Xml.XmlNode section) {

       XPathNavigator nav = section.CreateNavigator ();

      string typename = ( string ) nav.Evaluate ("string(@type)");

      Type t = Type.GetType ( typename );

       XmlSerializer ser = new XmlSerializer (t);

      return ser.Deserialize ( new XmlNodeReader (section));

    }

  }

}


It’s very, very simple. When you map a section of your configuration file to this handler, using an entry in your config file that looks like this:


< configuration >

  < configSections >

    < section name =" MyStuff "         t ype ="DevelopMentor.Candera.Utilities.XmlSerializerSectionHandler, Utilities"/>

  </ configSections >

</ configuration >


What happens is that any time you ask for the MyStuff section of the config file with code that looks like this:


ConfigurationSettings.GetConfig (" MyStuff ");


It will actually go look in the config file to figure out who knows how to deal with the “MyStuff” section. When it sees that it’s the XmlSerializerSectionHandler, it’ll create an instance of this object and call Create, passing it (via the section parameter) a reference to the relevant portion of the config file. In our case, it might look something like this:


< configuration >


   <!-- configSections element goes here -->  


  < MyStuff type =" SomeNamespace.MyStuff , CraigsConfig ">

    < Foo > 1.234 </ Foo >

    < Bar > A bunch of information </ Bar >

   </ MyStuff >


</ configuration >


What my handler does is to look for the “type” attribute on this bit of XML, in the form “classname, assemblyname”. In this case, it’s a class called MyStuff in a namespace SomeNamespace. It then – and here’s the good bit – uses the XmlSerializer to initialize an instance of this type from the XML in the configuration file. The XmlSerializer is a very cool piece of the .NET libraries, and you should check it out if you haven’t already. Basically, you write a type like this:



public class MyStuff

{

  private float foo ;

  private string bar;


  public float Foo

  {

    get { return foo ; }

    set { foo = value ; }

  }


  public string Bar

  {

     get { return bar; }

    set { bar = value ;

  }

}


And the XmlSerializer takes care of turning it into the XML above and vice versa. There are even a bunch of attributes you can use to control the process.


So given the section handler I wrote, any time I want to put some information in a config file, all I have to do is write a type like MyStuff, map a section to my XmlSerializerSectionWriter, write some XML into the config file with the values I’d like to capture and then ask the infrastructure to read it like this:


MyStuff ms = ( MyStuff ) ConfigurationSettings.GetConfig (" MyStuff ");

1、概述 log4net是.Net下一个非常优秀的开源日志记录组件。log4net记录日志的功能非常强大。它可以将日志分不同的等级,以不同的格式,输出到不同的媒介。本文主要是介绍如何在Visual Studio2008中使用log4net快速创建系统日志,如何扩展以输出自定义字段。 2、一个简单的使用实例 第一步:在项目中添加对log4net.dll的引用,这里引用版本是1.2.10.0。 第二步:程序启动时读取log4net配置文件。 如果是CS程序,在根目录的Program.cs中的Main方法中添加: log4net.Config.XmlConfigurator.Configure(); 如果是BS程序,在根目录的Global.asax.cs(没有新建一个)中的Application_Start方法中添加: log4net.Config.XmlConfigurator.Configure(); 无论BS还是CS程序都可直接在项目的AssemblyInfo.cs文件里添加以下的语句: [assembly: log4net.Config .XmlConfigurator()] 也可以使用自定义的配置文件,具体请参见4.4 关联配置文件。 第三步:修改配置文件。如果是CS程序,则在默认的App.config文件(没有新建一个)中添加内容;如果是BS程序,则添加到Web.config文件中,添加内容一样,这里不再列出。 App.config文件添加内容如下: <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <root> <level value="WARN" /> <appender-ref ref="LogFileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> <logger name="testApp.Logging"> <level value="DEBUG"/> </logger> <appender name="LogFileAppender" type="log4net.Appender.FileAppender" > <param name="File" value="log-file.txt" /> <param name="AppendToFile" value="true" /> <layout type="log4net.Layout.PatternLayout"> <param name="Header" value="[Header] "/> <param name="Footer" value="[Footer] "/> <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="DEBUG" /> <param name="LevelMax" value="WARN" /> </filter> </appender> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" > <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" /> </layout> </appender> </log4net> </configuration> 第四步:在程序使用。 log4net.ILog log = log4net.LogManager.GetLogger("testApp.Logging");//获取一个日志记录器 log.Info(DateTime.Now.ToString() + ": login success");//写入一条新log 这样就将信息同时输出到控制台和写入到文件名为“log-file.txt”的文件中,其中“log-file.txt”文件的路径是当前程序运行所在目录;也可以定义为绝对路径,配置如: <param name="File" value="C:/log-file.txt" />就写入C盘根目录下log-file.txt文件中
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值