一、首先下载log4net.dll http://pan.baidu.com/s/1gdigrwJ
二、添加log4net引用
三、代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using log4net; using System.Reflection; namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); //记录错误日志 log.Error("error", new Exception("发生了一个异常")); //记录严重错误 log.Fatal("fatal", new Exception("发生了一个致命错误")); //记录一般信息 log.Info("info"); //记录调试信息 log.Debug("debug"); //记录警告信息 log.Warn("warn"); } } }
四、config匹配
<log4net> <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL --> <!-- Set root logger level to ERROR and its appenders --> <root> <level value="ALL"/> <appender-ref ref="SysAppender"/> </root> <!-- Print only messages of level DEBUG or above in the packages --> <logger name="WebLogger"> <level value="DEBUG"/> </logger> <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net" > <param name="File" value="App_Data/" /> <param name="AppendToFile" value="true" /> <param name="RollingStyle" value="Date" /> <param name="DatePattern" value=""Logs_"yyyyMMdd".txt"" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> <param name="Header" value=" ----------------------header-------------------------- " /> <param name="Footer" value=" ----------------------footer-------------------------- " /> </layout> </appender> <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net"> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" /> </layout> </appender> </log4net>
五、如果想让log4net的config单独成log4net.config可以在程序集信息配置
代码:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "xml", Watch = true)]