我想将软件进程日志记录到文件中。我试图将Log4Net与ASP.NET MVC一起使用,而不是制作我自己的日志系统,但我在Visual Studio 2015中设置它时遇到了问题,如:
*.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)。
步骤1:使用Nuget获取log4net包:
步骤2:通过在Global.asax.cs
下的Application_Start()
文件中添加此调用,告诉log4net从XML配置(Web.config)初始化自己:
log4net.Config.XmlConfigurator.Configure();
步骤3:在标签<configSections>...</configSections>
之间添加Web.config中的配置部分:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
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>
现在,您已准备好调用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();
}