園子裡面有很多關於log4net保存到數據庫的帖子,但是要動手操作還是比較不易,從頭開始學習log4net數據庫日志一、WebConfig中配置log4net
下面先一點一點來學習如果進行配置
1.下載,2.數據庫腳本,請參考log4net保存到數據庫系列一:WebConfig中配置log4net
3.配置文件
#region 配置參數 string XmlValue = @" <log4net> <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> <root> <level value=""ALL"" /> <appender-ref ref=""AdoNetAppender"" /> </root> </log4net>"; #endregion 配置文件
4.讀取參數生成日志對象
XmlDocument log4netConfig = new XmlDocument(); log4netConfig.LoadXml(XmlValue);//讀取配置文件 ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); XmlConfigurator.Configure(rep, log4netConfig["log4net"]);
5.測試代碼
ILog log = LogManager.GetLogger(rep.Name, "test");
log.Debug("Message")
log.Info("log4net測試");
6.測試成功