An example of using log4net in MVC


Today, I want to make a log recording function myself. I’ve made it before but I forgot it. Today, I made it again. It took me several minutes to record it here

Step 1: add log4net.dll

Step 2: configuration example is as follows: I directly configured it under web.config

<?xml version="1.0" encoding="utf-8"?>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  <logger name="Student">
   <level value="ALL" />
   <appender-ref ref="rollingFile" />
  <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" />
<! -- not below!!! >
  <add key="webpages:Version" value="" />
  <add key="webpages:Enabled" value="false" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  <compilation debug="true" targetFramework="4.7.2" />
  <httpRuntime targetFramework="4.7.2" />

Step 3: add log4net. Config. Xmlconfigurator. Configure() to the global.asax.cs file, as follows:

  public class MvcApplication : System.Web.HttpApplication
    protected void Application_Start()

Step 4: add the log help class and use it. Note that the name corresponds to the comments in my code below

public class LogHelper
    //Student is the name value of your profile < logger name = "student" >
    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)
    public static void Info(object message)
    public static void Warn(object message)
    public static void Error(object message)
    public static void Error(object message, Exception e)
      log.Error(message, e);
    public static void Log(object message)

The content of the configuration file is relatively simple and detailed. Baidu can look at other details

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.