一、添加log4net的Nuget包
二、在Web.config或者App.config文件中添加log4net配置
代码:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<log4net>
<!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
<!-- Set root logger level to ERROR and its appenders -->
<!--<root>
<level value="ALL" />
<appender-ref ref="SysAppender" />
</root>
--> <!--Error日志-->
<logger name="LogError">
<level value="ERROR" />
<appender-ref ref="RollingLogFileAppender" />
</logger> <!--Info日志-->
<logger name="LogInfo">
<level value="INFO" />
<appender-ref ref="InfoAppender" />
</logger> <!--错误日志-->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log\\LogError\\" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value=""Logs_"yyyyMMdd".txt"" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<!--每条日志末尾的文字说明-->
<!--输出格式-->
<!--样例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info-->
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender> <!--Info日志-->
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log\\LogInfo\\" />
<param name="AppendToFile" value="true" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value=""Logs_"yyyyMMdd".txt"" />
<param name="RollingStyle" value="Date" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
</log4net>
三、在Global.asax全局文件中设置log4net使用的配置文件
代码:
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(Server.MapPath("~/Web.config")));
四、为了方便调用可以加个Help类
public class Logger
{
public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("LogInfo"); public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("LogError"); /// <summary>
/// 记录Info日志
/// </summary>
/// <param name="info"></param>
public static void Info(string info)
{
if (loginfo.IsInfoEnabled)
{
loginfo.Info(info);
}
} /// <summary>
/// 记录Error日志
/// </summary>
/// <param name="errorMsg"></param>
/// <param name="ex"></param>
public static void ErrorLog(string errorMsg, Exception ex = null)
{
if (logerror.IsErrorEnabled)
{
logerror.Error(errorMsg, ex);
}
}
}
接下来就可以使用了