也谈log4net 1.2.9 beta的使用(web 项目)
首先,配置文件由以前放在web.config文件里,改用单独的xml文件里了。例如,项目WebApp,它的配置文件就是WebApp.dll.log4net(扩展名也是可配置的,见下文)
<?xml version="1.0" encoding="utf-8" ?>
<log4net debug="false">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
<file value="webapp-log.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
</layout>
</appender>
<appender name="HttpTraceAppender" type="log4net.Appender.AspNetTraceAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log-data\rolling-log.txt" />
<appendToFile value="true" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<rollingStyle value="Size" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="HttpTraceAppender" />
<!-- <appender-ref ref="RollingLogFileAppender" /> -->
</root>
</log4net>
我觉得挺好这样,至少不用在web.config里配置节:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
然后在global文件里,添加代码(红色部分为添加的代码,蓝色部分为1.2.8之前的配置情况,大家可以比较一下):
Imports System.Web
Imports System.Web.SessionState
<Assembly: log4net.Config.XmlConfigurator(ConfigFileExtension:="log4net", Watch:=True)>
Public Class Global
Inherits System.Web.HttpApplication
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' 在应用程序启动时激发
'log4net.Config.DOMConfigurator.Configure()
End Sub
End Class
上面的代码
<Assembly: log4net.Config.XmlConfigurator(ConfigFileExtension:="log4net", Watch:=True)> 中log4net指的是前面配置文件WebApp.dll.log4net的扩展名。
最后,在项目里就可以运用了
... ....
Imports log4net
Namespace WebApp
Public Class WebForm1
Inherits System.Web.UI.Page
Private Shared ReadOnly log As ILog = LogManager.GetLogger(GetType(WebForm1))
先实现Ilog接口,然后用类似:
If log.IsDebugEnabled Then log.Debug("txtAdd1=[" & txtAdd1.Text & "] txtAdd2=[" & txtAdd2.Text & "]")
就可以了,还是挺简单的。