记录日志(Log4Net)
一:Log4net的简单示例
1、新建控制台应用程序,右键属性,把其框架.NET Framework4 Client Profile 修改为.NET Framework4,此时项目中将会自动添加一个App.config文件
内容如下:
<?xml version="1.0"?> <configuration> <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup> </configuration>
2、引用第三方类库:log4net.dll
3、在App.config文件中进行如下配置:
<?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <!-- Define some output appenders --> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="test.txt"/> <appendToFile value="true"/> <!--可存的日志文件的个数--> <maxSizeRollBackups value="10"/> <!--每个日志文件的大小--> <maximumFileSize value="1024KB"/> <rollingStyle value="Size"/> <staticLogFileName value="true"/> <layout type="log4net.Layout.PatternLayout"> <!--日志格式--> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/> </layout> </appender> <root> <!--日志记录的级别:None-Fatal(崩溃级别)-ERROR(错误级别)-WARN(警告级别)-DEBUG(bug级别)-INFO(信息级别)-ALL(所有)--> <level value="DEBUG"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration>
4、代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using log4net; namespace Log4Demo { class Program { static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure();//初始化配置 ILog log = log4net.LogManager.GetLogger("demo");//获取记录日志的实例 log.Debug("这是调试信息!"); } } }
5、日志文件就会写入项目根目录bin\Debug下的一个test.txt文件中。
二、在项目中的应用
1、有一个MVC项目,首先引用log4net.dll类库,然后在web.config中配置,添加标识中的内容:
<configuration> <!--新加配置内容--> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <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> <connectionStrings> <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" /> </connectionStrings> <!--新加配置内容结束--> <appSettings> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies> </compilation>
2、然后在Global.asax.cs问价中,初始化我们的配置:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); log4net.Config.XmlConfigurator.Configure();//初始化配置 }
3、在HomeController中添加代码如下:
public ActionResult Index() { ViewBag.Message = "欢迎使用 ASP.NET MVC!"; ViewData["count"] = GetCount.TotalCount(); try { int i = 0; int y = 10 / i; } catch (Exception exception) { ILog log = LogManager.GetLogger("demo"); log.Error("计算:" + exception.ToString()); } return View(); }
4、运行,自动生成日志文件。查看方式:右键,App_Data文件,在Windows资源管理器中打开,就会看到生成的日志文件。