简体   繁体   中英

How to configure or setup Log4Net with ASP.NET ( included MVC) C# on Visual Studio 2012 ~ ~

I want to record software process logs to files. Rather than make my own log system, I am trying to use Log4Net with ASP.NET MVC, but I have run into problems setting it up in Visual Studio 2015, like:

  1. How to setup web.config / Global.asax page?

  2. How to install components in VS 2012 ~?

  3. How to use it in my *.cs file?

What are the steps to properly configure Log4Net With ASP.NET MVC C# in Visual Studio 2015?

I also wrote a Q&A to set it up for ASP.NET WebForms, see How to use Log4net from Nuget with Visual Studio platform in the ASP.NET Web Form (Easy method) .

Step1: To use the Nuget to get the log4net package:

在此处输入图片说明

Step2: tell log4net to initialize itself from the XML configuration (Web.config), by adding this call in the Global.asax.cs file under Application_Start() :

log4net.Config.XmlConfigurator.Configure();

在此处输入图片说明

Step3: add the configuration section in Web.config between tag <configSections>...</configSections> :

  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

在此处输入图片说明

Step4: Insert the actual log4net configuration <log4net>...</log4net> (Within <configuration>...</configuration> but after the </configSections> tag) , see Apache log4net™ Config Examples for more examples:

<log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="logs\log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="100KB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>
    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>

在此处输入图片说明

Now you're ready to make calls to an ILog to write actual log statements to the configured appender(s):

ILog log = log4net.LogManager.GetLogger(typeof(HomeController));      

public ActionResult Index()
{
    log.Debug("Debug message");
    log.Warn("Warn message");
    log.Error("Error message");
    log.Fatal("Fatal message");
    ViewBag.Title = "Home Page";
    return View();
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM