如何在Visual Studio 2012上配置或设置带有ASP.NET(包含MVC)C#的Log4Net ~~

问题描述 投票:22回答:1

我想将软件进程日志记录到文件中。我试图将Log4Net与ASP.NET MVC一起使用,而不是制作我自己的日志系统,但我在Visual Studio 2015中设置它时遇到了问题,如:

  1. 如何设置web.config / Global.asax页面?
  2. 如何在VS 2012中安装组件〜?
  3. 如何在我的*.cs文件中使用它?

在Visual Studio 2015中使用ASP.NET MVC C#正确配置Log4Net的步骤是什么?

我还写了一个问答来为ASP.NET WebForms设置它,请参阅How to use Log4net from Nuget with Visual Studio platform in the ASP.NET Web Form (Easy method)

c# asp.net-mvc visual-studio asp.net-web-api log4net
1个回答
73
投票

步骤1:使用Nuget获取log4net包:

enter image description here

步骤2:通过在Global.asax.cs下的Application_Start()文件中添加此调用,告诉log4net从XML配置(Web.config)初始化自己:

log4net.Config.XmlConfigurator.Configure();

enter image description here

步骤3:在标签<configSections>...</configSections>之间添加Web.config中的配置部分:

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

enter image description here

Step4:插入实际的log4net配置<log4net>...</log4net>(在<configuration>...</configuration>内但在</configSections>标签之后),请参阅Apache log4net™ Config 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>

enter image description here

现在,您已准备好调用ILog将实际的日志语句写入已配置的appender:

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();
}

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.