1:下载log4net
http://logging.apache.org/log4net/download_log4net.cgi
2:引用到项目
下载以后,在项目中引用log4net.dll
3:加上下面这句话,指定log4net使用.config文件来读取配置信息。可以加在AssemblyInfo.cs(全局有效),也可以加在每个调用log4net的命名空间前
[assembly: log4net.Config.XmlConfigurator(Watch = true)
对于exe程序,需要 “程序名.exe.config”;对于网站,需要“web.config”
也可以自定义配置文件,比如我们新增一个log4net.config,这时就需要指定XmlConfigurator的ConfigFile属性。
(PS:记着修改log4net.config的属性,复制到输出目录:始终复制或者如果较新则复制)
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
4:在数据库中新建表
比如:
CREATE TABLE [dbo].[Log] ( [ID] [int] IDENTITY (1, 1) NOT NULL , [Date] [datetime] NOT NULL , [Thread] [varchar] (255) NOT NULL , [Level] [varchar] (20) NOT NULL , [Logger] [varchar] (255) NOT NULL , [Message] [varchar] (4000) NOT NULL ) ON [PRIMARY]
4:配置config
<?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> </configSections> <log4net> <logger name="logdb"> <level value="ALL" /> <appender-ref ref="AdoNetAppender_SqlServer" /> </logger> <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender" > <bufferSize value="1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="data source=(数据库地址);initial catalog=(数据库名称);integrated security=false;persist security info=True;User ID=(帐号);Password=(密码)" /> <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" /> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" /> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout" value="%thread" /> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout" value="%level" /> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout" value="%logger" /> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout" value="%message" /> </parameter> </appender> </log4net> </configuration>
5:写代码
using System;
namespace Test.Log4net
{
class Program
{
static void Main(string[] args)
{
log4net.ILog log = log4net.LogManager.GetLogger("logdb");
log.Debug("Test");
Console.ReadKey();
}
}
}