log4net 資料庫日誌 自定義欄位 ...
園子裡面有很多關於log4net保存到資料庫的帖子,但是要動手操作還是比較不易,從頭開始學習log4net資料庫日誌
下麵先一點一點來學習如果進行配置
1.下載安裝
- Nuget安裝:
- Nuget控制台安裝:
Install-Package log4net
- 官方下載最新版本:
http://logging.apache.org/log4net/download_log4net.cgi
2.創建資料庫腳本
1 CREATE TABLE [dbo].[Log] ( 2 [Id] [int] IDENTITY (1, 1) NOT NULL, 3 [Date] [datetime] NOT NULL, 4 [Thread] [varchar] (255) NOT NULL, 5 [Level] [varchar] (50) NOT NULL, 6 [Logger] [varchar] (255) NOT NULL, 7 [Message] [varchar] (4000) NOT NULL, 8 [Exception] [varchar] (2000) NULL 9 )資料庫腳本
3.配置文件
WebConfig的configSections節點增加
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
<log4net> <!--註冊Appender--> <root> <level value="ALL" /> <appender-ref ref="AdoNetAppender" /> </root> <!--配置Appender--> <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <bufferSize value="-1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="data source=[伺服器地址];initial catalog=[資料庫];persist security info=True;user id=[賬號];password=[密碼];MultipleActiveResultSets=True;" /> <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" /> <parameter> <parameterName value="@log_date" /> <dbType value="DateTime" /> <layout type="log4net.Layout.RawTimeStampLayout" /> </parameter> <parameter> <parameterName value="@thread" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="50" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="255" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="2000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> </appender> </log4net>WebConfig中配置log4net節點
4.設置監控
AssemblyInfo.cs中增加代碼
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
5.測試代碼
ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); log.Error("Error是錯誤", new Exception("錯誤")); log.Fatal("Fatal是嚴重錯誤", new Exception("致命錯誤")); log.Info("Info是普通消息"); log.Debug("Debug是調試消息");View Code
6.測試成功