1.下载log4net
2.新建Project,添加log4net.dll Reference
3.添加app.config文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- log4net的定义 -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<connectionStrings>
<!-- Example connection to a SQL Server Database on localhost. -->
<!-- <add name="ExampleConnectionString"
connectionString="Data Source=.;Initial Catalog=DBName;Integrated Security=True"
providerName="System.Data.SqlClient" /> -->
</connectionStrings>
<appSettings>
<!-- access these values via the property:
System.Configuration.ConfigurationManager.AppSettings[key]
-->
<add key="Setting1" value="Very" />
<add key="Setting2" value="Easy" />
</appSettings>
<log4net>
<!-- Console部分log输出格式的设定 -->
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger %c %message%newline" />
</layout>
</appender>
<!-- 日志文件部分log输出格式的设定 -->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs.log" />
<appendToFile value="true" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<rollingStyle value="Size" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<header value="[Header] " />
<footer value="[Footer] " />
<ConversionPattern value="%date [%thread] %-5level %logger [%c] %message%newline" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>
4.在AssemblyInfo.cs文件加入如下内容
[assembly: log4net.Config.XmlConfigurator()]
或
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
如果配置文件有改动,将自动检测到
5.测试代码
using System;
using log4net;
namespace log4netDemo
{
class Program
{
protected static readonly log4net.ILog mLog =LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void Main(string[] args)
{
mLog.Debug("debug");
mLog.Info("Hello World!");
mLog.Warn("Warn");
mLog.Error("Error");
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
附:捕获异常与java里的log4j类似,mLog.Error("Exception",e);