我们在开发系统时,都会需要记录系统的运行日志,下面简单的写了log4net在系统中的应用;
首先我们需要下载一个log4net的程序集,网上都能搜索得到。
在配置文件中进行配置,具体如下:
1、在配置文件的 <configSections>节点中加入如下配置:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
2、在<configuration>节点内对log4net 进行配置:
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!--定义文件存放位置-->
<param name="File" value="Logs/Log.txt" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="100" />
<param name="MaximumFileSize" value="1MB" />
<param name="RollingStyle" value="Size" />
<param name="StaticLogFileName" value="true" />
<param name="MaxSizeRollBackups" value="100" />
<layout type="log4net.Layout.PatternLayout">
<!--每条日志末尾的文字说明-->
<!--输出格式-->
<!--样例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info-->
<param name="ConversionPattern" value="%newline %date:%-5level %message" />
</layout>
</appender>
<logger name="Logger">
<level value="All" />
<appender-ref ref="RollingLogFileAppender" />
</logger>
</log4net>
3、创建一个类来对日志记录的操作:
using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Common
{
/// <summary>
/// 系统日志
/// </summary>
public class Log
{
private static Log systemlog = null;
private ILog log;
/// <summary>
/// 日志记录接口
/// </summary>
/// <returns></returns>
public static Log Instance
{
get
{
if (systemlog == null)
systemlog = new Log();
return systemlog;
}
}
/// <summary>
/// 初始化日志
/// </summary>
public Log()
{
log = log4net.LogManager.GetLogger("Logger");
}
public ILog Log4
{
get { return log; }
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="message"></param>
public void Info(object message)
{
Log4.Info(message);
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Info(object message, Exception e)
{
Log4.Info(message, e);
}
/// <summary>
/// 写Error级日志
/// </summary>
/// <param name="message"></param>
public void Error(object message)
{
Log4.Error(message);
}
/// <summary>
/// 写Error级日志
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Error(object message, Exception e)
{
Log4.Error(message, e);
}
/// <summary>
/// 写Debug级日志
/// </summary>
/// <param name="message"></param>
public void Debug(object message)
{
Log4.Debug(message);
}
/// <summary>
/// 写Debug级日志
/// </summary>
/// <param name="message"></param>
/// <param name="e"></param>
public void Debug(object message, Exception e)
{
Log4.Debug(message, e);
}
}
}
以上log4net的引用就已经完成,在使用时我们可以直接调用该类来写日志了:
try
{
}
catch (Exception ex)
{
Log.Instance.Error(ex);
}
原文地址:http://blog.csdn.net/houxingding/article/details/46346271