您的位置:首页 > 其它

log4net 使用方法

2015-06-14 17:46 162 查看
1、下载http://mirror.bit.edu.cn/apache//logging/log4net/binaries/log4net-1.2.13-bin-newkey.zip, 解压,复制log4net.dll到项目目录,添加引用;

2、在项目中添加应用程序配置文件 app.config:

<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<!--定义输出到文件中-->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--定义文件存放位置-->
<file value="log\\"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/>
<staticLogFileName value="false"/>
<param name="MaxSizeRollBackups" value="100"/>
<layout type="log4net.Layout.PatternLayout">
<!--每条日志末尾的文字说明-->
<!--输出格式-->
<!--样例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info-->
<conversionPattern value="%n[%date] 线程ID: [%thread] %-5level 类:%logger property: [%property{NDC}] - 错误描述:%message"/>
</layout>
</appender>

<root>
<level value="ERROR"/>
<!--文件形式记录日志-->
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>


3、在AssemblyInfo.cs中添加一行,目的是启用log4net:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]


4、写一个logHelper类,方便实用。

/// <summary>
/// 日志辅助类
/// </summary>
public class LogHelper
{
private static ILog log;
private static LogHelper logHelper = null;
/// <summary>
/// 初始化
/// </summary>
/// <returns></returns>
public static ILog GetInstance()
{
logHelper = new LogHelper(null);

return log;
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="configPath"></param>
/// <returns></returns>
public static ILog GetInstance(string configPath)
{
logHelper = new LogHelper(configPath);

return log;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="configPath"></param>
private LogHelper(string configPath)
{
if (!string.IsNullOrEmpty(configPath))
{
log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(configPath));
}
else
{
log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
}
}

}
}


更多参考:
http://www.cnblogs.com/dragon/archive/2005/03/24/124254.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: