ASP.NET MVC中使用log4net的实现示例
这篇文章主要介绍了ASP.NET MVC中使用log4net的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
今天自己要弄一个日志记录功能,以前也弄过 但是都忘了,今天又弄了一下 花了几十分钟,在此记录一下
第一步:添加log4net.dll
第二步:配置 示例如下: 我是直接配置在了Web.config下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <? xml version = "1.0" encoding = "utf-8" ?> < configuration > < configSections > < section name = "log4net" type = "log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </ configSections > < log4net > < logger name = "Student" > < level value = "ALL" /> < appender-ref ref = "rollingFile" /> </ logger > < appender name = "rollingFile" type = "log4net.Appender.RollingFileAppender,log4net" > < File value = "log/" /> < DatePattern value = "yyyy-MM-dd".txt"" /> < StaticLogFileName value = "false" /> < maxSizeRollBackups value = "-1" /> < RollingStyle value = "Date" /> < AppendToFile value = "false" /> < MaximumFileSize value = "1024MB" /> < layout type = "log4net.Layout.PatternLayout,log4net" > < ConversionPattern value = "%-38m %-7p %-20d %n" /> </ layout > </ appender > </ log4net > <!--下面的不是!!!--> < appSettings > < add key = "webpages:Version" value = "3.0.0.0" /> < add key = "webpages:Enabled" value = "false" /> < add key = "ClientValidationEnabled" value = "true" /> < add key = "UnobtrusiveJavaScriptEnabled" value = "true" /> </ appSettings > < system.web > < compilation debug = "true" targetFramework = "4.7.2" /> < httpRuntime targetFramework = "4.7.2" /> </ system.web > </ configuration > |
第三步:在Global.asax.cs文件下添加 log4net.Config.XmlConfigurator.Configure(); 如下:
1 2 3 4 5 6 7 8 9 10 11 | public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); log4net.Config.XmlConfigurator.Configure(); } } |
第四步:添加Log帮助类 然后使用即可 这里需要注意的是名字对应 看我的下面代码中的注释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public class LogHelper { //Student是你的配置文件 <logger name="Student"> 的name的值 private static log4net.ILog log = log4net.LogManager.GetLogger( "Student" ); public static void Debug( object message, Exception e) { log.Debug(message, e); } public static void Debug( object message) { log.Debug(message); } public static void Info( object message) { log.Info(message); } public static void Warn( object message) { log.Warn(message); } public static void Error( object message) { log.Error(message); } public static void Error( object message, Exception e) { log.Error(message, e); } public static void Log( object message) { log.Info(message); } } |
配置文件的内容比较简略 详细的自己百度看看其他比较详细的即可
以上就是本文的全部内容,希望对大家的学习有所帮助