今天自己要弄一个日志记录功能,以前也弄过 但是都忘了,今天又弄了一下 花了几十分钟,在此记录一下
第一步:添加log4net.dll
第二步:配置 示例如下: 我是直接配置在了Web.config下
<?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(); 如下:
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帮助类 然后使用即可 这里需要注意的是名字对应 看我的下面代码中的注释
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); } }
新闻热点
疑难解答
图片精选