日期:2014-06-10 浏览次数:20391 次
1.引用log4net.dll文件
2.添加配置文件
1 <?xml version="1.0"?> 2 <configuration> 3 <configSections> 4 <!--log4net配置安装--> 5 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> 6 </configSections> 7 <log4net> 8 <!--记录器root可以被其他继承--> 9 <root> 10 <level value="ALL" /> 11 <appender-ref ref="ConsoleAppender" /> 12 <appender-ref ref="FileAppender" /> 13 </root> 14 <!--记录器OtherClass这个类才有的日志级别--> 15 <logger name="log4netSample.OtherClass"> 16 <level value="DEBUG"/> 17 <appender-ref ref="ConsoleAppender"/> 18 <appender-ref ref="FileAppender" /> 19 </logger> 20 <!--输出到控制台--> 21 <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender,log4net"> 22 <layout type="log4net.Layout.PatternLayout,log4net"> 23 <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> 24 </layout> 25 </appender> 26 27 <!--<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> 28 <layout type="log4net.Layout.PatternLayout"> 29 <conversionPattern value="%date{ABSOLUTE} 30 [%thread] %level %logger - %message%newline"/> 31 </layout> 32 <filter type="log4net.Filter.StringMatchFilter"> 33 <stringToMatch value="test" /> 34 </filter> 35 <filter type="log4net.Filter.DenyAllFilter" /> 36 </appender>--> 37 38 <!--保存到文件--> 39 <appender name="FileAppender" type="log4net.Appender.FileAppender"> 40 <file value="mylogfile.txt" /> 41 <appendToFile value="true" /> 42 <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> 43 <layout type="log4net.Layout.PatternLayout"> 44 <conversionPattern value="%date [%thread] %level %logger - %message%newline" /> 45 </layout> 46 <filter type="log4net.Filter.LevelRangeFilter"> 47 <levelMin value="INFO" /> 48 <levelMax value="FATAL" /> 49 </filter> 50 </appender> 51 </log4net> 52 <startup> 53 <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> 54 </startup> 55 </configuration>
3.读取配置信息
也可以在每次调用的地方
1 log4net.Config.XmlConfigurator.Configure();
4.调用
1 namespace log4netSample 2 { 3 public class OtherClass 4 { 5 public static void Log4NetSayHello() { 6 log4net.Config.XmlConfigurator.Configure(); 7 log4net.ILog logger = log4net.LogManager.GetLogger(typeof(OtherClass)); 8 logger.Error("这也是一个日志消息"); 9 } 10 } 11 }
1 namespace log4netSample 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Program)); 8 logger.Debug("这是一个日志消息"); 9 10 OtherClass.Log4NetSayHello(); 11 Console.ReadKey(); 12 } 13 } 14 }