• EnterpriseLibrary6.0 log2database


    1、引用EnterpriseLibrary6.0相关dll

    2、安装Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix

      主要为了方便编辑config文件,不是必须安装,安装后需要更改解决方案属性,将Enterprise Library v6 binaries path 指向企业库6.0的bin目录

    3、执行sql脚本创建记录日志的数据库、存储过程、表

      下载的包中提供了脚本,目录:Enterprise Library 6devguidesamplesLoggingScriptsLoggingDatabase.sql

    4、配置config文件

     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

    5、实例代码

     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

    6、注意事项

      记录日志到数据库代码中需要加入以下代码,否则会报错

    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

      调试中异常信息并不能写入数据库,编译后以管理员身份运行会才能写入数据库,解决方法待确认

      事件查看器发布后可以写入日志需要对Event Log Listener中的source做以下操作

      <!-- source 值为 Enterprise Library Logging
      就需要在注册表
      HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesEventLogApplication
      上右键加一个项名称也叫 Enterprise Library Logging 否则发布后日志不会成功记录
      -->

  • 相关阅读:
    【Java】【IDE】【Jetbrain Idea】Intellij IDEA 快捷键整理
    【Linux】【Services】【KVM】virsh命令详解
    【Linux】【Services】【KVM】安装与简单配置
    【Linux】【Services】【Docker】Docker File
    【Linux】【Services】【Docker】网络
    【Linux】【Services】【Docker】应用
    【Linux】【Services】【Docker】基础理论
    【Python】【Module】json and pickle
    【Python】【Module】hashlib
    Highcharts 对数组的要求
  • 原文地址:https://www.cnblogs.com/servant/p/6526058.html
Copyright © 2020-2023  润新知