效果圖:html
1:第一步建立SQL表結構-
CREATE TABLE [dbo].[LogDetails] (
-
[LogID] int NOT NULL IDENTITY( 1, 1) ,
-
[LogDate] datetime NOT NULL ,
-
[LogThread] nvarchar( 100) NOT NULL ,
-
[LogLevel] nvarchar( 200) NOT NULL ,
-
[LogLogger] nvarchar( 500) NOT NULL ,
-
[LogMessage] nvarchar( 3000) NOT NULL ,
-
[LogActionClick] nvarchar( 4000) NULL ,
-
[UserName] nvarchar( 30) NULL ,
-
[UserIP] varchar( 20) NULL
-
)
2:建立項目而後下載log4net.dll 在項目中添加引用 http://logging.apache.org/log4net/download_log4net.cgi下載Binaries 下面的web
3:建立 log4net.config數據庫
-
<?xml version="1.0" encoding="utf-8" ?>
-
-
<log4net debug="false">
-
<!-- name屬性指定其名稱,type則是log4net.Appender命名空間的一個類的名稱,意思是,指定使用哪一種介質-->
-
<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
-
<!--日誌緩存寫入條數 設置爲0時只要有一條就馬上寫到數據庫-->
-
<bufferSize value="0" />
-
<!--日誌數據庫鏈接串-->
-
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
-
<connectionString value="DATABASE=GoodLook;SERVER=xx.xx.140.170;UID=sa;PWD=123456a;Connect Timeout=30;" />
-
<!--日誌數據庫腳本-->
-
<commandText value="INSERT INTO LogDetails ([LogDate],[LogThread],[LogLevel],[LogLogger],[LogActionClick],[LogMessage],[UserName],[UserIP]) VALUES (@log_date, @thread, @log_level, @logger, @ActionsClick, @message,@UserName,@UserIP)" />
-
<!--日誌時間LogDate -->
-
<parameter>
-
<parameterName value="@log_date" />
-
<dbType value="DateTime" />
-
<layout type="log4net.Layout.RawTimeStampLayout" />
-
</parameter>
-
<!--線程號-->
-
<parameter>
-
<parameterName value="@thread" />
-
<dbType value="String" />
-
<size value="100" />
-
<layout type="log4net.Layout.PatternLayout">
-
<conversionPattern value="%t" />
-
</layout>
-
</parameter>
-
<!--日誌類型LogLevel -->
-
<parameter>
-
<parameterName value="@log_level" />
-
<dbType value="String" />
-
<size value="200" />
-
<layout type="log4net.Layout.PatternLayout">
-
<conversionPattern value="%p" />
-
</layout>
-
</parameter>
-
<!--日誌名稱-->
-
<parameter>
-
<parameterName value="@logger" />
-
<dbType value="String" />
-
<size value="500" />
-
<layout type="log4net.Layout.PatternLayout">
-
<conversionPattern value="%logger" />
-
</layout>
-
</parameter>
-
<parameter>
-
<parameterName value="@message" />
-
<dbType value="String" />
-
<size value="3000" />
-
<layout type="Log4NetApply.MyLayout">
-
<conversionPattern value="%property{Message}" />
-
</layout>
-
</parameter>
-
<parameter>
-
<parameterName value="@ActionsClick" />
-
<dbType value="String" />
-
<size value="4000" />
-
<layout type="Log4NetApply.MyLayout" >
-
<conversionPattern value = "%property{ActionsClick}"/>
-
</layout>
-
</parameter>
-
<!--自定義UserName -->
-
<parameter>
-
<parameterName value="@UserName" />
-
<dbType value="String" />
-
<size value="30" />
-
<layout type="Log4NetApply.MyLayout" >
-
<!--log4net.MDC.Set("UserName", "asdfasdf");
-
<conversionPattern value = "%X{UserName}"/>-->
-
<conversionPattern value = "%property{UserName}"/>
-
</layout>
-
</parameter>
-
<parameter>
-
<parameterName value="@UserIP" />
-
<dbType value="String" />
-
<size value="20" />
-
<layout type="Log4NetApply.MyLayout" >
-
<conversionPattern value = "%property{UserIP}"/>
-
</layout>
-
</parameter>
-
</appender>
-
<!-- setup the root category, add the appenders and set the default level -->
-
<root>
-
<level value="Warn"/> <!-- 定義記錄的日誌級別-->
-
<level value="Info"/>
-
<level value="Debug"/>
-
<level value="Fine"/>
-
<appender-ref ref="ADONetAppender" /> <!-- 記錄到什麼介質中-->
-
</root>
-
<!-- specify the level for some specific categories -->
-
<!--//關於上邊root到logger這塊,若是同時出現,有可能會出現重複插入記錄的狀況:-->
-
<!--<logger name="iNotes">
-
<level value="WARN"/>
-
<level value="INFO"/>
-
<level value="DEBUG"/>
-
<level value="FINE"/>
-
<appender-ref ref="ADONetAppender"/>
-
</logger>
-
<logger name="StellaLogger">
-
<level value="ALL"/>
-
<appender-ref ref="AdoNetAppender" />
-
</logger>-->
-
<appender name="ReflectionLayout" type="log4net.Appender.RollingFileAppender,log4net">
-
-
<!--日誌文件路徑,按文件大小方式輸出時在這裏指定文件名,而且前面的日誌按天在文件名後自動添加當天日期造成文件-->
-
<param name="File" value="D:/Log/" />
-
-
<!--是否追加到文件-->
-
<param name="AppendToFile" value="true" />
-
-
<!--記錄日誌寫入文件時,不鎖定文本文件-->
-
<!--<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />-->
-
-
<!--Unicode編碼-->
-
<!--<Encoding value="UTF-8" />-->
-
-
<!--最多產生的日誌文件數,value="-1"爲不限文件數-->
-
<!--<param name="MaxSizeRollBackups" value="10" />-->
-
-
<!--是否只寫到一個文件中-->
-
<param name="StaticLogFileName" value="false" />
-
-
<!--按照何種方式產生多個日誌文件(日期[Date],文件大小[Size],混合[Composite])-->
-
<param name="RollingStyle" value="Composite" />
-
-
<!--按日期產生文件夾,文件名[在日期方式與混合方式下使用]-->
-
<param name="DatePattern" value="yyyy-MM-dd/"ReflectionLayout.log"" />
-
<!--<param name="DatePattern" value="yyyyMMdd/yyyyMMdd"-TimerServer.log"" />-->
-
<!--<param name="DatePattern" value="yyyyMMdd/"TimerServer/TimerServer.log"" />-->
-
-
<!--每一個文件的大小。只在混合方式與文件大小方式下使用,超出大小的在文件名後自動增長1從新命名-->
-
<param name="maximumFileSize" value="500KB" />
-
-
<!--記錄的格式。-->
-
<layout type="TGLog.ExpandLayout2.ReflectionLayout,TGLog">
-
<param name="ConversionPattern" value="記錄時間:%date 線程ID:[%thread] 日誌級別:%-5level 記錄類:%logger 操做者ID:%property{Operator} 操做類型:%property{Action}%n 當前機器名:%property%n當前機器名及登陸用戶:%username %n 記錄位置:%location%n 消息描述:%property{Message}%n 異常:%exception%n 消息:%message%newline%n%n" />
-
</layout>
-
</appender>
-
-
-
-
-
</log4net>
4:在Web.config 裏面加 configSections 節點 (CS可直接寫在app.config裏面,或者都寫在一個config裏面)apache
-
<configuration>
-
<strong> <span style="color:#FF0000;"> <configSections>
-
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
-
</configSections>
-
<log4net configSource="log4net.config"/> </span> </strong>
-
-
<system.web>
-
<compilation debug="true" targetFramework="4.5" />
-
<httpRuntime targetFramework="4.5" />
-
</system.web>
-
-
</configuration>
5:Properties 屬性下面的AssemblyInfo.cs 追加 必須有這個,不然寫入不到數據庫中
-
//[assembly: log4net.Config.XmlConfigurator(Watch = true)]
-
//注意: ConfigFile 能夠指定相對路徑 和 絕對路徑。 eg: /log/xxxx.log 或者 d://log//xxxx.log
-
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
6:添加 Global.asax
而後在Application_Start 追加 讀取配置程序文件緩存
-
protected void Application_Start(object sender, EventArgs e)
-
{
-
//應用程序啓動時,自動加載配置log4Net
-
XmlConfigurator.Configure();
-
}
-
using log4net.Layout;
-
using log4net.Layout.Pattern;
-
using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Reflection;
-
using System.Web;
-
-
namespace Log4NetApply
-
{
-
/// <summary>
-
/// 包含了全部的自定字段屬性
-
/// </summary>
-
public class LogContent
-
{
-
public LogContent(string macAddress, string computerName, string actionsclick, string description)
-
{
-
UserIP = macAddress;
-
UserName = computerName;
-
ActionsClick = actionsclick;
-
Message = description;
-
}
-
-
/// <summary>
-
/// 訪問IP
-
/// </summary>
-
public string UserIP { get; set; }
-
-
/// <summary>
-
/// 系統登錄用戶
-
/// </summary>
-
public string UserName { get; set; }
-
-
/// <summary>
-
/// 動做事件
-
/// </summary>
-
public string ActionsClick { get; set; }
-
-
/// <summary>
-
/// 日誌描述信息
-
/// </summary>
-
public string Message { get; set; }
-
-
-
}
-
public class MyLayout : PatternLayout
-
{
-
public MyLayout()
-
{
-
this.AddConverter( "property", typeof(LogInfoPatternConverter));
-
}
-
}
-
-
public class LogInfoPatternConverter : PatternLayoutConverter
-
{
-
-
protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
-
{
-
if (Option != null)
-
{
-
// Write the value for the specified key
-
WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
-
}
-
else
-
{
-
// Write all the key value pairs
-
WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
-
}
-
}
-
/// <summary>
-
/// 經過反射獲取傳入的日誌對象的某個屬性的值
-
/// </summary>
-
/// <param name="property"></param>
-
/// <returns></returns>
-
-
private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
-
{
-
object propertyValue = string.Empty;
-
PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
-
if (propertyInfo != null)
-
propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
-
return propertyValue;
-
}
-
}
-
}
8:示例使用
-
try
-
{
-
log.Info( new LogContent( "127.0.0.1", "111111", "登錄系統", "登錄成功"));
-
var ss = 1 - int.Parse( "sss");
-
}
-
catch(Exception ex)
-
{
-
log.Error( new LogContent( "127.0.0.1", "111111", "登錄系統", ex.Message+ ":"+ex.StackTrace));
-
}
其餘自行參考下列文章
-
http://www.cnblogs.com/kissazi2/p/3393151.html
-
http://blog.csdn.net/zdw_wym/article/details/48802821
-
http://blog.csdn.net/ydm19891101/article/details/50561638
-
http://www。w2bc。com/Article/70140
-
http://www.cnblogs.com/yuangang/archive/2016/05/16/5497140.html
出處:https://blog.csdn.net/kongwei521/article/details/52242319app