1.下载log4net,解开压缩包(如果不需重新编译,可直接跳至第4步)
2.下载nant,解开压缩包,把其中的bin目录的路径添加到系统环境变量Path中
3.用build编译log4net,生成log4net.dll
4.在要使用log4net的项目中引用log4net
5.新建应用程序配置文件,使用默认的命名App.Config即可,属性设置为复制到输出目录.
编译的时候编译器会自动将其拷贝为项目名称.exe.config,
6.配置文件样例
<?xml version="1.0" encoding="utf-8" ?>
<!--
.NET application configuration file
This file must have the exact same name as your application with
.config appended to it. For example if your application is ConsoleApp.exe
then the config file must be ConsoleApp.exe.config it mut also be in the
same directory as the application.
-->
<configuration>
<!-- Register a section handler for the log4net section -->
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<!-- Enable internal debugging in log4net -->
<appSettings>
<!-- To enable internal log4net logging specify the following appSettings key -->
<!-- <add key="log4net.Internal.Debug" value="true"/> -->
</appSettings>
<!-- This section contains the log4net configuration settings -->
<log4net debug="false">
<appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
<param name="File" value="Application.log.txt" />
<param name="datePattern" value="MM-dd HH:mm" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="_LogDataLog.txt" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="10" />
<param name="MaximumFileSize" value="5MB" />
<param name="RollingStyle" value="Size" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
7.在program.cs中的namespace上面写入以下代码:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
8.在要使用log4net的类中声明log4net变量:
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
9.配置完毕.使用方法如下:
log.info("Hello");
本文详细介绍了如何配置和使用log4net进行日志记录。包括下载与编译log4net、配置应用程序配置文件、在项目中引用log4net等步骤,并提供了具体的XML配置示例。





