EnterpriseLibrary6.0 log2database

一、引用EnterpriseLibrary6.0相關dllsql

二、安裝Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix數據庫

  主要爲了方便編輯config文件,不是必須安裝,安裝後須要更改解決方案屬性,將Enterprise Library v6 binaries path 指向企業庫6.0的bin目錄ide

三、執行sql腳本建立記錄日誌的數據庫、存儲過程、表ui

  下載的包中提供了腳本,目錄:Enterprise Library 6\devguidesamples\Logging\Scripts\LoggingDatabase.sqlspa

四、配置config文件3d

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <configuration>
 3   <!--微軟企業庫6.0 配置Begin-->
 4   <configSections>
 5     <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
 6     <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
 7   </configSections>
 8 
 9 
10   <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
11     <listeners>
12       <add name="Event Log Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
13         listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
14         source="Enterprise Library Logging" formatter="Text Formatter"
15         log="" machineName="." traceOutputOptions="None" />
16       <add name="Database Trace Listener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
17         listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
18         databaseInstanceName="LoggingCore" writeLogStoredProcName="WriteLog"
19         addCategoryStoredProcName="AddCategory" />
20     </listeners>
21     <formatters>
22       <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
23         template="Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"
24         name="Text Formatter" />
25     </formatters>
26     <categorySources>
27       <add switchValue="All" name="General">
28         <listeners>
29           <add name="Event Log Listener" />
30           <add name="Database Trace Listener" />
31         </listeners>
32       </add>
33     </categorySources>
34     <specialSources>
35       <allEvents switchValue="All" name="All Events">
36         <listeners>
37           <add name="Database Trace Listener" />
38           <add name="Event Log Listener" />
39         </listeners>
40       </allEvents>
41       <notProcessed switchValue="All" name="Unprocessed Category">
42         <listeners>
43           <add name="Database Trace Listener" />
44           <add name="Event Log Listener" />
45         </listeners>
46       </notProcessed>
47       <errors switchValue="All" name="Logging Errors &amp; Warnings">
48         <listeners>
49           <add name="Event Log Listener" />
50           <add name="Database Trace Listener" />
51         </listeners>
52       </errors>
53     </specialSources>
54   </loggingConfiguration>
55   <!--微軟企業庫6.0 配置End-->
56 
57   <!--指定默認數據庫 必須配置-->
58   <dataConfiguration defaultDatabase="myDataBase" />
59   <connectionStrings>
60     <add name="myDataBase" connectionString="Initial Catalog=EricTest;Data Source=127.0.0.1;UID=sa;Password=Az.123456;"
61       providerName="System.Data.SqlClient" />
62     <add name="LoggingCore" connectionString="Initial Catalog=Logging;Data Source=127.0.0.1;UID=sa;Password=Az.123456;"
63       providerName="System.Data.SqlClient" />
64   </connectionStrings>
65   <startup>
66     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
67   </startup>
68 </configuration>
View Code

五、實例代碼調試

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Microsoft.Practices.EnterpriseLibrary.Data;
 7 using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
 8 using System.Data.Common;
 9 using System.Data;
10 using Microsoft.Practices.EnterpriseLibrary.Logging;
11 
12 namespace EntLib6Test
13 {
14     class Program
15     {
16 
17         static void Main(string[] args)
18         {
19 
20             IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
21             DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(configurationSource), false);
22             LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
23             Logger.SetLogWriter(logWriterFactory.Create(), false);
24 
25 
26             string sql = @"SELECT Name from T_UserBase";
27 
28             DatabaseProviderFactory factory = new DatabaseProviderFactory();
29             Database db = factory.CreateDefault();
30 
31             using (DbCommand sqlCmd = db.GetSqlStringCommand(sql))
32             {
33                 DataSet userList = db.ExecuteDataSet(sqlCmd);
34 
35                 if (userList != null && userList.Tables.Count > 0 && userList.Tables[0].Rows.Count > 0)
36                 {
37                     for (int i = 0; i < userList.Tables[0].Rows.Count; i++)
38                     {
39                         Console.WriteLine(userList.Tables[0].Rows[i]["Name"].ToString());
40                     }
41                 }
42             }
43 
44 
45 
46             try
47             {
48                 int a = 1;
49                 int b = 0;
50                 int c = a / b;
51             }
52             catch (Exception ex)
53             {
54                 LogEntry logEntry = new LogEntry();
55                 logEntry.EventId = 1;
56                 logEntry.Priority = 1;
57                 logEntry.Severity = System.Diagnostics.TraceEventType.Error;
58                 logEntry.Title = "標題";
59                 logEntry.Message = "錯誤信息"+ex.Message;
60                 logEntry.Categories.Add("EntLib6");
61 
62                 Logger.Writer.Write(logEntry, "General");
63                 Console.WriteLine("日誌寫入完成!");    
64 
65             }
66 
67             Console.ReadKey();
68         }
69     }
70 }
View Code

六、注意事項日誌

  記錄日誌到數據庫代碼中須要加入如下代碼,不然會報錯code

1             IConfigurationSource configurationSource = ConfigurationSourceFactory.Create();
2             DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(configurationSource), false);
3             LogWriterFactory logWriterFactory = new LogWriterFactory(configurationSource);
4             Logger.SetLogWriter(logWriterFactory.Create(), false);
View Code

  調試中異常信息並不能寫入數據庫,編譯後以管理員身份運行會才能寫入數據庫,解決方法待確認orm

 

  事件查看器發佈後能夠寫入日誌須要對Event Log Listener中的source作如下操做

  <!-- source 值爲 Enterprise Library Logging   就須要在註冊表   HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application   上右鍵加一個項名稱也叫 Enterprise Library Logging 不然發佈後日志不會成功記錄   -->

相關文章
相關標籤/搜索