.net中日至框架log4net.dll如何使用
时间:2011-05-25 来源:上校
首先配置web.config文件
1.添加如下节点
<!--log4net配置 BEGIN-->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net debug="true">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="SysLog/ErrorLog.txt"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
</layout>
</appender>
<logger name="File">
<level value="All" />
<appender-ref ref="LogFileAppender" />
</logger>
</log4net>
<!--log4net配置 END-->
2.然后配置global.asax
void Application_Start(object sender, EventArgs e)
{
//注册日志配置
log4net.Config.XmlConfigurator.Configure();
}
void Application_Error(object sender, EventArgs e)
{
//在出现未处理的错误时运行的代码
NetFan.Core.Logger.Log.Error(e.ToString());
}
3.新建一个全局使用的类Logger
/// <summary>
/// 类,事件日志类。
/// 单态封装log4net
/// </summary>
public class Logger
{
private static log4net.ILog log = null;
private static object lockHelper = new object();
public static log4net.ILog Log
{
get
{
if (log == null)
lock (lockHelper)
if (log == null)
log = log4net.LogManager.GetLogger("File");
return log;
}
}
}
4.上面ok后, 就可以使用了.
方法是:
Try
{
//处理信息
}
catch(Exception ex)
{
//出错后执行日志.IP如果是127.0.0.1可以不用写入日志.
Logger.Log.Error("错误来自:"+Request.UserHostAddress,ex);
}
公司项目的配置:
<configuration>
<configSections>
<section name="SSO" type="SXT.SSO.Client.SSOEntry,SXT.SSO.Client"/>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
......
<!--log4net配置 BEGIN-->
<log4net debug="true">
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="../Log/RES"/>
<AppendToFile value="true"/>
<rollingstyle value="date"/>
<datePattern value="yyyy-MM-dd'.log'"/>
<StaticLogFileName value="false"/>
<maxSizeRollBackups value="100"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 错误描述:%message%newline"/>
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="debug"/>
<appender-ref ref="LogFileAppender"/>
<!--<appender-ref ref="ConsoleAppender"/>-->
</root>
</log4net>
<!--log4net配置 END-->