Log4net.dll记录日志的使用
2017-12-18 本文已影响58人
张中华
参考学习网址:
http://blog.csdn.net/weifangyh/article/details/8524380
http://blog.csdn.net/dragon_ton/article/details/71601339
https://www.cnblogs.com/kissazi2/p/3392094.html
https://www.cnblogs.com/zeroone/p/3606160.html
1.新建一个控制台应用程序,在项目中引用log4net.dll,然后项目中添加一个配置文件log4net.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<log4net debug="false">
<appender name="ApplePushFileAppender"
type="log4net.Appender.RollingFileAppender">
<param name="File"
value="Logs\\ApplePush" />
<!--日志路径-->
<param name="AppendToFile" value="true"/>
<!--日志生成追加在文件中-->
<param name="DatePattern" value=".yyyyMMdd".log"" />
<!--生成日志文件名称的格式-->
<param name="RollingStyle" value="Date"/>
<!--日志重复方式,按照日期重复,每天产生一个日志文件-->
<param name="StaticLogFileName" value="false"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
</root>
<logger name="ApplePush">
<!--日志名字,需要跟后面代码中的名字一样-->
<appender-ref ref="ApplePushFileAppender" />
</logger>
</log4net>
</configuration>
2.新建一个loggerhelper类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using System.Reflection;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
namespace TestLog4Net
{
public static class LoggerHelper
{
private static ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// 获取当前 Ilog 对象
/// </summary>
public static ILog GetILog
{
get
{
return log;
}
}
/// <summary>
/// 记录错误日志
/// </summary>
/// <param name="message"></param>
/// <param name="ex"></param>
public static void Error(object message, Exception ex)
{
log.Error(message, ex);
}
/// <summary>
/// 记录严重错误
/// </summary>
/// <param name="message"></param>
/// <param name="ex"></param>
public static void Fatal(object message, Exception ex)
{
log.Fatal(message, ex);
}
/// <summary>
/// 记录一般信息
/// </summary>
/// <param name="message"></param>
public static void Info(object message)
{
log.Info(message);
}
/// <summary>
/// 记录调试信息
/// </summary>
/// <param name="message"></param>
public static void Debug(object message)
{
log.Debug(message);
}
/// <summary>
/// 记录警告信息
/// </summary>
/// <param name="message"></param>
public static void Warn(object message)
{
log.Warn(message);
}
}
}