How to use asp. net log4net

  • 2021-07-21 08:15:45
  • OfStack

At the beginning of contact with asp. net, how can there be less log records, so simply record the configuration and use of log4net in case you forget it later.

First of all, introduce log4net. dll, and download this file from Baidu.

Then configure the configuration under 1, and add it under configuration node in web. config


<configSections>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
 </configSections>
 <log4net>
 <appender name="rollingFile" type="log4net.Appender.RollingFileAppender,log4net">
 <param name="File" value="log/" />
 <param name="AppendToFile" value="true" />
 <param name="RollingStyle" value="Date" />
 <param name="DatePattern" value="yyyy-MM-dd&quot;.log&quot;" />
 <param name="StaticLogFileName" value="false" />
 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%n%r %p[%d %c] %m%n" />
 </layout>
 </appender>
 <root>
 <level value="ALL" />
 <appender-ref ref="rollingFile" />
 </root>
 
 <logger name="WebLogger">
 <level value="ALL" />
 <appender-ref ref="rollingFile" />
 </logger>
 </log4net>

Then add in the Application_Start method of Global. asax


log4net.Config.XmlConfigurator.Configure();

Finally, write a log output class, which is convenient to call


public class MyLog
{
 
 private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebLogger");
 
 public MyLog()
 {
 
 }
 private static void SetConfig()
 {
 object o = ConfigurationManager.GetSection("log4net");
 log4net.Config.XmlConfigurator.Configure(o as System.Xml.XmlElement);
 }
 
 public static void LogInfo(string Message)
 {
 if (!log.IsInfoEnabled)
 SetConfig();
 log.Info(Message);
 }
 
 public static void LogInfo(string Message, Exception ex)
 {
 if (!log.IsInfoEnabled)
 SetConfig();
 log.Info(Message, ex);
 }
 public static void ErrorInfo(string Message)
 {
 if (!log.IsInfoEnabled)
 SetConfig();
 log.Error(Message);
 }
 
 public static void DebugInfo(string Message)
 {
 if (!log.IsInfoEnabled)
 SetConfig();
 log.Debug(Message);
 }
}

Then you can use log output in various codes!

The configuration of log4net has not been carefully looked at for the time being, and we will continue to study it when we are free.


Related articles: