你好,LOG4NET

类别:.NET开发 点击:0 评论:0 推荐:

你好LOG4NET
-----在C#中使用LOG4NET

1.下载log4net (Google log4net)
2.unzip log4net
3.运行VS,新建 c# Windows应用程序。
4.添加引用Log4NET
5.新建一个应用程序配置文件App.config(具体内容附在后面)
6.打开Form1.cs,
  在Namespace上添加一行  [assembly: log4net.Config.DOMConfigurator(Watch=true)]
  在类Form1中添加一个静态变量
                private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

7.添加一个按钮。在按钮处理函数中添加一行 log.Warn("你好!");

8.运行程序。点一下按钮。

OK,打开Bin\Debug\log-file.txt,可以看到“你好”。


附.App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <!-- Register a section handler for the log4net section -->
 <configSections>
  <section name="log4net" type="System.Configuration.IgnoreSectionHandler" />
 </configSections>
 <appSettings>
  <!-- To enable internal log4net logging specify the following appSettings key -->
  <!-- <add key="log4net.Internal.Debug" value="true"/> -->
 </appSettings>
 <!-- This section contains the log4net configuration settings -->
 <log4net>
  <!-- Define some output appenders -->
  <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
   <param name="File" value="log-file.txt" />
   <!-- Example using environment variables in params -->
   <!-- <param name="File" value="${TMP}\\log-file.txt" /> -->
   <param name="AppendToFile" value="true" />
   <!-- An alternate output encoding can be specified -->
   <!-- <param name="Encoding" value="unicodeFFFE" /> -->
   <layout type="log4net.Layout.PatternLayout">
    <param name="Header" value="[Header]\r\n" />
    <param name="Footer" value="[Footer]\r\n" />
    <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] &lt;%X{auth}&gt; - %m%n" />
   </layout>
   <!-- Alternate layout using XML   
   <layout type="log4net.Layout.XMLLayout" /> -->
  </appender>

  <!-- Setup the root category, add the appenders and set the default level -->
  <root>
   <level value="ALL" />
   <appender-ref ref="LogFileAppender" />
   <!-- <appender-ref ref="A" /> -->
  </root>
  
  <!-- Specify the level for some specific categories -->
  <logger name="SLog4net.Form1">
   <!-- <appender-ref ref="B" /> -->
   <level value="ALL" />
   <appender-ref ref="RollingLogFileAppender" />
  </logger>
 </log4net>
</configuration>

本文地址:http://com.8s8s.com/it/it42897.htm