Logging Application Block with IBM DB2

Topics: Logging Application Block
Apr 1, 2011 at 2:30 PM
Hi,
I am using Ent Lib 5.0 with .NET Framework 4.0. I am also using DB2 database and below are my challenges.
 
1) Logging to Text File works like a charm, but to the database it neither logs nor gives me any error.
2) Is it possible that I log all the Info to the Text File and all the errors to the Database? I guess I might need to use the Custom Trace Listener?
 
I tried referring the libraries through the Program Files as well as by GACing them but no success.
 
Below is the config file I am using. Could you please help me coz I am stuck with this since quite sometime.
 
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <!--<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />-->
  </configSections>


  <loggingConfiguration name="" tracingEnabled="true" defaultCategory="General">
    <listeners>
      <add name="RxCRollingFileTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        fileName="MYCOMPANY.Pharmacy.RxClinical.RxCEngine.WindowConsole1.log"
        footer="" formatter="Text Formatter" header="" rollInterval="Day" />
      <!--<add name="RxCDatabaseTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        databaseInstanceName="RxCDatabaseInstance" writeLogStoredProcName="RxCWriteLogToDB"
        addCategoryStoredProcName="Errors" formatter="Text Formatter"
        traceOutputOptions="None" filter="Error" />-->
    </listeners>
    <formatters>
      <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        template="Timestamp: {timestamp}Message: {message}" name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="RxCRollingFileTraceListener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events">
        <listeners>
          <add name="RxCRollingFileTraceListener" />
        </listeners>
      </allEvents>
      <notProcessed switchValue="All" name="Unprocessed Category">
        <listeners>
          <add name="RxCRollingFileTraceListener" />
        </listeners>
      </notProcessed>
      <errors switchValue="All" name="Logging Errors &amp; Warnings">
        <listeners>
          <add name="RxCRollingFileTraceListener" />
        </listeners>
      </errors>
    </specialSources>
  </loggingConfiguration>
  <exceptionHandling>
    <exceptionPolicies>
      <add name="RethrowPolicy">
        <exceptionTypes>
          <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="NotifyRethrow">
            <exceptionHandlers>
              <add name="Rethrow Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                exceptionMessage="this is custom rethrow handler message from moiz."
                exceptionMessageResourceType="" wrapExceptionType="System.DivideByZeroException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
      <add name="ReplacePolicy">
        <exceptionTypes>
          <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="ThrowNewException">
            <exceptionHandlers>
              <add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                exceptionMessage="this is custom replace handler message from moiz."
                replaceExceptionType="System.DivideByZeroException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
      <add name="WrapPolicy">
        <exceptionTypes>
          <add name="All Exceptions" type="System.Exception, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="None">
            <exceptionHandlers>
              <add name="Wrap Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                exceptionMessage="this is custom wrap handler message from moiz."
                wrapExceptionType="System.DivideByZeroException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>
<dataConfiguration defaultDatabase="RxCDatabaseInstance">
  </dataConfiguration>
  <connectionStrings>
    <add name="RxCDatabaseInstance" connectionString="Database=DB;User ID=UID;Password=PWD;Server=SERVERNAME;Persist Security Info=True;CurrentSchema=GHTR;Connect Timeout=0;"
      providerName="IBM.Data.DB2" />
  </connectionStrings>
<system.data>
    <DbProviderFactories>      
        <add name="IBM DB2 .NET Data Provider" invariant="IBM.Data.DB2" description="IBM DB2 Data Provider for .NET Framework 2.0" type="IBM.Data.DB2.DB2Factory, IBM.Data.DB2, Version=9.0.0.2, Culture=neutral, PublicKeyToken=7c307b91aa13d208"/>
    </DbProviderFactories>
  </system.data>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

C# Code Here:

  LogEntry lEntry = new LogEntry( );

            StringBuilder sBuilder = new StringBuilder();
            string sInfo = sBuilder.Append(" TYPE: ").Append(typeName).Append(" ORIGIN: ").Append(origin).Append(" THREADID:  ").Append(threadId).Append(" MESSAGE: ").Append(message).ToString();
            lEntry.Message = sInfo;
            
            //Write LogEntry to the Sink
            Logger.Write(lEntry);

            //Write LogEntry to the Console
            Console.WriteLine(sInfo);

Apr 4, 2011 at 1:51 AM

Hi,

1) Logging to Text File works like a charm, but to the database it neither logs nor gives me any error.
	- In this case you need to use a Custom Trace Listener and implements there the logging to your DB2 database. This thread will give you an idea on how to create a custom trace listener that logs to a database.

2) Is it possible that I log all the Info to the Text File and all the errors to the Database? I guess I might need to use the Custom Trace Listener?
 	You don't need to use a Custom Trace Listener. You just have to create a category with 2 listeners one for a flat file and the other one is pointing to database. Then specify on the Severity Filter of each listener. Here is a sample snippet:
	<listeners>
            <add name="LogInfo" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        fileName="trace.log" formatter="Text Formatter" filter="Information" />
      <add name="LogErrors" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        databaseInstanceName="LocalSqlServer" writeLogStoredProcName="WriteLog"
        addCategoryStoredProcName="AddCategory" formatter="Text Formatter"
        filter="Error" />
    </listeners> 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Apr 4, 2011 at 3:37 PM



Thanks Noel,

I implemented the code as below but I am getting the error which says:

ERROR Message = 

"The type Database cannot be constructed. You must configure the container to supply this value."
PLEASE HELP!!!!!

CONFIG FILE:

<?xml version="1.0" encoding="utf-8"?>
<configuration>  
    <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
        <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <loggingConfiguration name="LoggingApplicationBlock" tracingEnabled="true"
        defaultCategory="General">
        <listeners>           
            <add name="RxCTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                databaseInstanceName="RxCDatabase" writeLogStoredProcName="GHTR.RxCWriteLogToDB"
                addCategoryStoredProcName="General" />
        </listeners>
        <formatters>
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                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})}"
                name="Text Formatter" />
        </formatters>
        <categorySources>
            <add switchValue="All" name="General">
                <listeners>
                    <add name="RxCTraceListener" />
                </listeners>
            </add>
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events" />
            <notProcessed switchValue="All" name="Unprocessed Category" />
            <errors switchValue="All" name="Logging Errors &amp; Warnings">
                <listeners>
                    <add name="RxCTraceListener" />
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
    <dataConfiguration defaultDatabase="RxCDatabase" />
    <connectionStrings>
      <add name="RxCDatabase" connectionString="Data Source=local;Initial Catalog=Employee_Database;Integrated Security=SSPI;"
 providerName="System.Data.SqlClient"/>      
    </connectionStrings>
</configuration>


C# CODE:

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Data;
using IBM.Data.DB2;
using System.Configuration;
namespace WindowsFormsApplication1
{
    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class MyTraceListener:CustomTraceListener
    {                
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
        {
            //if (data is LogEntry && data != null)
            {

                //Database db = DatabaseFactory.CreateDatabase(ConfigurationManager.ConnectionStrings["RxCDatabase"].ConnectionString);
                //using (var dbConnection = new IBM.Data.DB2.DB2Connection(ConfigurationManager.ConnectionStrings["RxCDatabase"].ConnectionString))
                {
                    try
                    {
                        Database db = DatabaseFactory.CreateDatabase(ConfigurationManager.ConnectionStrings["RxCDatabase"].ConnectionString);

                        //DB2Connection db2Conn = new DB2Connection();
                        DB2Command cmd = new DB2Command("GHTR.RXCWriteLogToDB");
                        cmd.CommandType = CommandType.StoredProcedure;
                        //cmd.CommandType = CommandType.Text;
                        ExtendedLogEntry le = (ExtendedLogEntry)data;

                        //string insertSQL = "INSERT INTO GHTR.RXC_LOG_TEST VALUES(DEFAULT,'" + le.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'," + le.ProgramId + ",'" + le.UserId + "','" + le.MachineName + "'," + le.ThreadId + ",'" + le.Level + "','" + le.Logger + "','" + le.Message
                            //+ "'," + le.JobId + ",'" + le.AddOperId + "','" + le.AddTimeStamp.ToString("yyyy-MM-dd HH:mm:ss.fff") + "','" + le.LastOperId + "','" + le.LastTimeStamp.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'" + ");";


                        //cmd.Parameters.Add(new DB2Parameter("log_TimeStmp",le.TimeStamp));
                        //cmd.Parameters.Add(new DB2Parameter("prog_Id", le.ProgramId));
                        //cmd.Parameters.Add(new DB2Parameter("userId", le.UserId));
                        //cmd.Parameters.Add(new DB2Parameter("machineName", le.MachineName));
                        //cmd.Parameters.Add(new DB2Parameter("threadId", le.ThreadId));
                        //cmd.Parameters.Add(new DB2Parameter("lvl", le.Level));
                        //cmd.Parameters.Add(new DB2Parameter("logger", le.Logger));
                        //cmd.Parameters.Add(new DB2Parameter("msg", le.Message));
                        //cmd.Parameters.Add(new DB2Parameter("job_Id", le.JobId));
                        //cmd.Parameters.Add(new DB2Parameter("add_Oper_Id", le.AddOperId));
                        //cmd.Parameters.Add(new DB2Parameter("add_Time_Stmp", le.AddTimeStamp));
                        //cmd.Parameters.Add(new DB2Parameter("last_Oper_Id", le.LastOperId));
                        //cmd.Parameters.Add(new DB2Parameter("last_Time_Stmp", le.LastTimeStamp));

                        //cmd.CommandText = insertSQL;
                        //dbConnection.Open();
                        //cmd.Connection = dbConnection;
                        //cmd.ExecuteNonQuery();


                        db.AddInParameter(cmd, "log_TimeStmp", DbType.DateTime,  le.TimeStamp);
                        db.AddInParameter(cmd, "prog_Id", DbType.Int32, le.ProgramId);
                        db.AddInParameter(cmd, "userId", DbType.String,  le.UserId);
                        db.AddInParameter(cmd, "machineName", DbType.String, le.MachineName);
                        db.AddInParameter(cmd, "threadId", DbType.String, le.ThreadId);
                        db.AddInParameter(cmd, "lvl", DbType.String,le.Level);
                        db.AddInParameter(cmd, "logger", DbType.DateTime, le.Logger);
                        db.AddInParameter(cmd, "msg", DbType.String, le.Message);
                        db.AddInParameter(cmd, "job_Id", DbType.String, le.JobId);
                        db.AddInParameter(cmd, "add_Oper_Id", DbType.String, le.AddOperId);
                        db.AddInParameter(cmd, "add_Time_Stmp", DbType.DateTime, le.AddTimeStamp);
                        db.AddInParameter(cmd, "last_Oper_Id", DbType.String, le.LastOperId);
                        db.AddInParameter(cmd, "last_Time_Stmp", DbType.DateTime,le.TimeStamp);
                        db.ExecuteNonQuery(cmd);
                    }

                    catch (Exception ex)
                    {
                        
                    }
                }
            }
        }

        public override void Write(string message)
        {
            throw new NotImplementedException();
        }

        public override void WriteLine(string message)
        {
            throw new NotImplementedException();
        }
    }


    public class ExtendedLogEntry : LogEntry
    {

        public DateTime TimeStamp { get; set; }
        public int ProgramId { get; set; }
        public string UserId { get; set; }
        public string MachineName { get; set; }
        public int ThreadId { get; set; }
        public string Level { get; set; }
        public string Logger { get; set; }
        public string Message { get; set; }
        public int JobId { get; set; }
        public string AddOperId { get; set; }
        public DateTime AddTimeStamp { get; set; }
        public string LastOperId { get; set; }
        public DateTime LastTimeStamp { get; set; }
    }


}


Apr 4, 2011 at 4:12 PM

Bingo!!!,Now it has started logging to the Database but the Filtering is not working.No Matter what I put below in the filter criteria whether Error / Information it logs to the Database.

WHAT AM I MISSING PLEASE HELP.

CONFIG FILE:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
        <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <loggingConfiguration name="LoggingApplicationBlock" tracingEnabled="true"
        defaultCategory="General">
        <listeners>          
            <add name="RxCTraceListener" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                databaseInstanceName="RxCDatabase" writeLogStoredProcName="GHTR.RxCWriteLogToDB"
                addCategoryStoredProcName="General" filter ="Information"  />
        </listeners>
        <formatters>
            <add type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                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})}"
                name="Text Formatter" />
        </formatters>
        <categorySources>
            <add switchValue="All" name="General">
                <listeners>
                    <add name="RxCTraceListener" />
                </listeners>
            </add>
        </categorySources>
        <specialSources>
            <allEvents switchValue="All" name="All Events" />
            <notProcessed switchValue="All" name="Unprocessed Category" />
            <errors switchValue="All" name="Logging Errors &amp; Warnings">
                <listeners>
                    <add name="RxCTraceListener" />
                </listeners>
            </errors>
        </specialSources>
    </loggingConfiguration>
    <dataConfiguration defaultDatabase="RxCDatabase" />
    <connectionStrings>
        <add name="RxCDatabase" connectionString="Database=DB2WIN;User ID=UID;Password=#PWD;Server=SERVERNAME;Persist Security Info=True;CurrentSchema=MYSCHEMA;Connect Timeout=0;"
       providerName="IBM.Data.DB2"/>            
    </connectionStrings>
</configuration>


C# CODE:

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Data;
using IBM.Data.DB2;
using System.Configuration;
namespace WindowsFormsApplication1
{
    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class MyTraceListener:CustomTraceListener
    {               
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
        {
       
            if (data is LogEntry && data != null)
            {
                using (var dbConnection = new IBM.Data.DB2.DB2Connection(ConfigurationManager.ConnectionStrings["RxCDatabase"].ConnectionString))
                {
                    try
                    {
                        ExtendedLogEntry le = (ExtendedLogEntry)data;
                        le.Severity = TraceEventType.Error;
                        DB2Command cmd = new DB2Command("GHTR.RXCWriteLogToDB");
                        cmd.CommandType = CommandType.StoredProcedure;                       

                        cmd.Parameters.Add(new DB2Parameter("log_TimeStmp", le.TimeStamp));
                        cmd.Parameters.Add(new DB2Parameter("prog_Id", le.ProgramId));
                        cmd.Parameters.Add(new DB2Parameter("userId", le.UserId));
                        cmd.Parameters.Add(new DB2Parameter("machineName", le.MachineName));
                        cmd.Parameters.Add(new DB2Parameter("threadId", le.ThreadId));
                        cmd.Parameters.Add(new DB2Parameter("lvl", le.Level));
                        cmd.Parameters.Add(new DB2Parameter("logger", le.Logger));
                        cmd.Parameters.Add(new DB2Parameter("msg", le.Message));
                        cmd.Parameters.Add(new DB2Parameter("job_Id", le.JobId));
                        cmd.Parameters.Add(new DB2Parameter("add_Oper_Id", le.AddOperId));
                        cmd.Parameters.Add(new DB2Parameter("add_Time_Stmp", le.AddTimeStamp));
                        cmd.Parameters.Add(new DB2Parameter("last_Oper_Id", le.LastOperId));
                        cmd.Parameters.Add(new DB2Parameter("last_Time_Stmp", le.LastTimeStamp));

                        dbConnection.Open();
                        cmd.Connection = dbConnection;
                        cmd.ExecuteNonQuery();
                    }

                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }

        }

        public override void Write(string message)
        {
            throw new NotImplementedException();
        }

        public override void WriteLine(string message)
        {
            throw new NotImplementedException();
        }
    }


    public class ExtendedLogEntry : LogEntry
    {
        public DateTime TimeStamp { get; set; }
        public int ProgramId { get; set; }
        public string UserId { get; set; }
        public string MachineName { get; set; }
        public int ThreadId { get; set; }
        public string Level { get; set; }
        public string Logger { get; set; }
        public string Message { get; set; }
        public int JobId { get; set; }
        public string AddOperId { get; set; }
        public DateTime AddTimeStamp { get; set; }
        public string LastOperId { get; set; }
        public DateTime LastTimeStamp { get; set; }
    }


}




Apr 5, 2011 at 1:47 AM
Edited Apr 5, 2011 at 1:54 AM

 

I just noticed that in your config, you are filtering severity type of 'Information'. You need to change it to 'Error'.

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Apr 5, 2011 at 2:04 AM

That's what I am saying. It shouldnt be logging if the Severity I am passing is Error, but it is logging.

Apr 5, 2011 at 2:56 AM
Edited Apr 5, 2011 at 3:41 AM

If I understand it correctly, what you want to happen here is if the severity filter of your trace listener is set to Information, when you pass a log with Error severity, it will not log since the trace listener is set to accept Information only and not Error? If this is what you want to achieve then unfortunately you need to create a custom trace listener for this. By design, filtering by severity follows a hierarchy. The hierarchy goes like this: Verbose > Information > Warning > Error > Critical. If you set Information as your filter then it will also accept Warning, Error and Critical as well.

 

Noel Angelo Bolasoc
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com