1.引用log4net.dll
2.寫配置文件config/log4net.config
< ?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configsections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configsections>
<log4net>
<root>
<!--
<level value="ALL" />
<appender -ref ref="rootFile" />
-->
</root>
<logger name="Default">
<level value="DEBUG" />
<appender -ref ref="rollingFile" />
</logger>
<appender name="rollingFile"
type="log4net.Appender.RollingFileAppender,log4net" >
<lockingmodel type="log4net.Appender.FileAppender+MinimalLock" />
<param name="File" type="" value="log/" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Composite" />
<param name="MaxSizeRollBackups" value="10"/>
<maximumfilesize value="1MB" />
<param name="DatePattern" value="yyyy-MM-dd".log"" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern"
value="%d %file [%t] %-5p %c [%x] - %m%n" />
<param name="Header" value=" ----------------------
header-------------------------- " />
<param name="Footer" value=" ----------------------
footer-------------------------- " />
</layout>
</appender>
</log4net>
</configuration>
3.創建Global.asax
void Application_Start(object sender, EventArgs e)
{
//在應用程序啟動時運行的代碼
log4net.Config.DOMConfigurator.Configure
(new System.IO.FileInfo(Server.MapPath("config/log4net.config")));
}
4.創建輔助類Loghelper.cs
public class LogHelper
{
private static ILog _log;
public static ILog log
{
get
{
if (_log == null)
{
_log = log4net.LogManager.GetLogger("Default");
}
return _log;
}
}
public static void debug(string message)
{
if (log.IsDebugEnabled)
{
log.Debug(message);
}
}
public static void error(string message)
{
if (log.IsErrorEnabled)
{
log.Error(message);
}
}
public static void fatal(string message)
{
if (log.IsFatalEnabled)
{
log.Fatal(message);
}
}
public static void info(string message)
{
if (log.IsInfoEnabled)
{
log.Info(message);
}
}
public static void warn(string message)
{
if (log.IsWarnEnabled)
{
log.Warn(message);
}
}
}
5.調用
protected void Page_Load(object sender, EventArgs e)
{
LogHelper.debug("測試信息");
}
2009.2.6:
Win程序須在AssemblyInfo.cs加如下一句
[assembly: log4net.Config.DOMConfigurator(ConfigFile="config/log4net.config", Watch = true)]