Error in Custom Trace Listener--Urgent Help Reuired

Topics: Logging Application Block
Mar 30, 2009 at 1:13 PM
Edited Mar 30, 2009 at 1:15 PM
hi..
 i want to log some additional information using Logging Application Block( i am using EL 3.1 and .Net 2.0 with VS 2005)

i found this http://entlib.codeplex.com/Thread/View.aspx?ThreadId=49721

and followed it

i ran batch file which created "Logging" database in  MS SQL 2005. it have three tables
Category
Category
Log

i added "UserName" column in Log table and modified "WriteLog" stored procedure also

i created new Class by inheriting from CustomTraceListener. when i run this code it gives me this error


"""System.ArgumentException was unhandled
  Message="The type 'CustomDatabaseLogging.DatabaseCutomTraceListener, CustomDatabaseTraceListener' cannot be resolved. Please verify the spelling is correct or that the full type name is provided." """



please take a look at my code and let me now where the error is....



using System;
using System.Collections.Generic;
using System.Text;

using System.Data.Common;
using System.Data;

using System.Diagnostics;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace CustomDatabaseLogging
{
    [ConfigurationElementType(typeof(CustomTraceListenerData))]
    public class DatabaseCutomTraceListener : CustomTraceListener
    {

        public override void Write(string message)
        {
            throw new Exception("The method or operation is not implemented.");
        }
        public override void Write(Object o)
        {
            LogEntry log = o as LogEntry;
            Database db = DatabaseFactory.CreateDatabase();

            DbCommand cmd = db.GetStoredProcCommand("WriteLog");

            db.AddInParameter(cmd, "eventID", DbType.Int32, log.EventId);
            db.AddInParameter(cmd, "priority", DbType.Int32, log.Priority);
            db.AddParameter(cmd, "severity", DbType.String, 32, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Severity.ToString());
            db.AddParameter(cmd, "title", DbType.String, 256, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Title);
            db.AddInParameter(cmd, "timestamp", DbType.DateTime, log.TimeStamp);
            db.AddParameter(cmd, "machineName", DbType.String, 32, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.MachineName);
            db.AddParameter(cmd, "AppDomainName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.AppDomainName);
            db.AddParameter(cmd, "ProcessID", DbType.String, 256, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ProcessId);
            db.AddParameter(cmd, "ProcessName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ProcessName);
            db.AddParameter(cmd, "ThreadName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ManagedThreadName);
            db.AddParameter(cmd, "Win32ThreadId", DbType.String, 128, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Win32ThreadId);
            db.AddParameter(cmd, "message", DbType.String, 1500, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Message);
            db.AddInParameter(cmd, "formattedmessage", DbType.String, log.Message);

            IDictionary<String, object> dictionary = log.ExtendedProperties;
            dictionary["UserName"].ToString();

            db.AddInParameter(cmd, "UserName", DbType.String, dictionary["UserName"]);

            db.AddOutParameter(cmd, "LogId", DbType.Int32, 4);

            db.ExecuteNonQuery(cmd);
            int logId = Convert.ToInt32(cmd.Parameters[cmd.Parameters.Count - 1].Value);


            //return logId;
            //throw new Exception("The method or operation is not implemented.");
        }

        public override void WriteLine(string message)
        {            
            throw new Exception("The method or operation is not implemented.");
        }
    }
}

App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </configSections>
  <loggingConfiguration name="Logging Application Block" tracingEnabled="true"
    defaultCategory="General" logWarningsWhenNoCategoriesMatch="true">
    <listeners>
      <add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        type="CustomDatabaseLogging.DatabaseCutomTraceListener, CustomDatabaseTraceListener"
        name="Custom Trace Listener"
        formatter="Text Formatter"
        />    
      
    </listeners>
    <formatters>
      <add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
        name="Text Formatter" />
    </formatters>
    <categorySources>
      <add switchValue="All" name="General">
        <listeners>
          <add name="Custom Trace Listener" />
        </listeners>
      </add>
    </categorySources>
    <specialSources>
      <allEvents switchValue="All" name="All Events" />
      <notProcessed switchValue="All" name="Unprocessed Category" />
      <errors switchValue="All" name="Logging Errors &amp; Warnings" />
    </specialSources>
  </loggingConfiguration>
  <connectionStrings>
    <add name="Connection String" connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=Logging;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

and here is tester program from which i am using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace CustomDatabaseLogging
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LogEntry log = new LogEntry();
            log.EventId = 222;
            log.Priority = 1;
            log.Title = "Main";
            log.Message = "Main Method Executed";
            log.Categories.Add("General");           
            Dictionary<String, Object> dictionary = new Dictionary<string, object>();

            dictionary.Add("UserName", "admin");

            Logger.Write(log);                         //at this line i am getting above mentioned exception
        }
    }
}


there is no error while compiling time...
Mar 31, 2009 at 7:43 AM
Hi,

What is the assembly name where the DatabaseCutomTraceListener resides? The might have been a problem with the full type name that you've provided. Please verfy that the full type name is correct. With the code snippets that you've provided i guess that the full type name should be "CustomDatabaseLogging.DatabaseCutomTraceListener, CustomDatabaseLogging".


Valiant Dudan

Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com
Mar 31, 2009 at 8:14 AM
still i am getting this error


The type 'CustomDatabaseLogging.DatabaseCutomTraceListener, CustomDatabaseLogging' cannot be resolved. Please verify the spelling is correct or that the full type name is provided.
Mar 31, 2009 at 8:29 AM
Is your DatabaseCutomTraceListener in a different project? if it is, try to reference the project from your host application (your test program). Then again, check the full type name for correctness.

Valiant Dudan
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com


Mar 31, 2009 at 8:40 AM
ya its separate and i have already added its reference.. i decided to write my own code to log in database and file. Thanks for  helping :)
Apr 1, 2009 at 10:51 PM
Hi Valiant,
        I am also getting the same what mohsan87 was getting earlier. I checked all the the steps that you suggested. But still i am getting this error when i run this line Logger.Write(log); 

The type 'CustomDatabaseLogging.DatabaseCutomTraceListener, CustomDatabaseLogging' cannot be resolved. Please verify the spelling is correct or that the full type name is provided.

Do let me know what i have to do to fix this.

Apr 2, 2009 at 4:48 AM
Hi,

I was able to repro this error when (1) I have the correct full type name but dont have reference to the project where the custom trace listener resides. (2) i have a reference but I dont give the correct full type name. Did you use the type picker to associate your Custom trace listener or you just manually typed it? If possible send me a copy of your solution so I can take a closer look.


Valiant Dudan
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com
Apr 2, 2009 at 4:32 PM
Hi Valiant,
     Here is my code below. Few things what works here. I am using Enterprise Library 4.1 configuration for generating app.config. I am not doing anything with app.config manually. Once i compiled my custom databse listener i register that assembly to GAC as suggested so that i can pull ths custom listener type in app.config. I was able to pull this type using the type picker associated with Custom trace listener as you mentioned above. Validate configuration was fine. Then i added reference to my form based project. Here i tried two approaches.

1. Initially i added reference of custom dll from bin directory as that dll was not listed under .NET dlls category. (it didn;t work) got the below error :

The current build operation (build key Build Key[Microsoft.Practices.EnterpriseLibrary.Logging.LogWriter, null]) failed: The type 'CustomLogger.CustomDatabaseErrorLoggerListener, CustomLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8c838048d8c129bb' cannot be resolved. Please verify the spelling is correct or that the full type name is provided. (Strategy type ConfiguredObjectStrategy, index 2)

2. Then i added the reference from GAC folder "C:\WINDOWS\assembly\GAC_MSIL\CustomLogger\1.0.0.0__8c838048d8c129bb" just want to make sure that both the app,config and referenced dlls are same one. Still got the above error :-(


Please do let me know what could be the problem. Hope my explanation should be able to proceed you to look in detail.

App.Config :- 


<

 

configuration>

 

<

 

configSections>

 

<

 

section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

 

<

 

section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />

 

</

 

configSections>

 

<

 

loggingConfiguration name="Logging Application Block" tracingEnabled="true"

 

 

 

defaultCategory="" logWarningsWhenNoCategoriesMatch="true">

 

<

 

listeners>

 

<

 

add listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.CustomTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

 

 

 

traceOutputOptions="None" filter="All" type="CustomLogger.CustomDatabaseErrorLoggerListener, CustomLogger, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8c838048d8c129bb"

 

 

 

name="Custom Trace Listener" initializeData="" />

 

<

 

add databaseInstanceName="ConnectionString" writeLogStoredProcName="WriteLog"

 

 

 

addCategoryStoredProcName="AddCategory" formatter="Text Formatter"

 

 

 

listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Database.Configuration.FormattedDatabaseTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

 

 

 

traceOutputOptions="None" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.Database.FormattedDatabaseTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging.Database, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

 

 

 

name="Database Trace Listener" />

 

<

 

add toAddress="elango@ctsinternational.com" fromAddress="elango@ctsinternational.com"

 

 

 

subjectLineStarter="Test" subjectLineEnder="Testing Error" smtpServer="cts8a"

 

 

 

smtpPort="25" formatter="Email Text Formatter" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.EmailTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

 

 

 

traceOutputOptions="Timestamp" filter="All" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.EmailTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

 

 

 

name="Email TraceListener" />

 

</

 

listeners>

 

<

 

formatters>

 

<

 

add template="Extended Properties: {dictionary({key} || {value}&#xD;&#xA;)}"

 

 

 

type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

 

 

 

name="Text Formatter" />

 

<

 

add template="Timestamp: {timestamp}&#xD;&#xA;Message: {message}&#xD;&#xA;Category: {category}&#xD;&#xA;Priority: {priority}&#xD;&#xA;EventId: {eventid}&#xD;&#xA;Severity: {severity}&#xD;&#xA;Title:{title}&#xD;&#xA;Machine: {machine}&#xD;&#xA;Application Domain: {appDomain}&#xD;&#xA;Process Id: {processId}&#xD;&#xA;Process Name: {processName}&#xD;&#xA;Win32 Thread Id: {win32ThreadId}&#xD;&#xA;Thread Name: {threadName}&#xD;&#xA;Extended Properties: {dictionary({key} - {value}&#xD;&#xA;)}"

 

 

 

type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"

 

 

 

name="Email Text Formatter" />

 

</

 

formatters>

 

<

 

categorySources>

 

<

 

add switchValue="All" name="Audit">

 

<

 

listeners>

 

<

 

add name="Database Trace Listener" />

 

</

 

listeners>

 

</

 

add>

 

<

 

add switchValue="All" name="Custom">

 

<

 

listeners>

 

<

 

add name="Custom Trace Listener" />

 

</

 

listeners>

 

</

 

add>

 

<

 

add switchValue="All" name="ErrorMail">

 

<

 

listeners>

 

<

 

add name="Email TraceListener" />

 

</

 

listeners>

 

</

 

add>

 

<

 

add switchValue="All" name="General" />

 

</

 

categorySources>

 

<

 

specialSources>

 

<

 

allEvents switchValue="All" name="All Events" />

 

<

 

notProcessed switchValue="All" name="Unprocessed Category" />

 

<

 

errors switchValue="All" name="Logging Errors &amp; Warnings" />

 

</

 

specialSources>

 

</

 

loggingConfiguration>

 

<

 

dataConfiguration defaultDatabase="ConnectionString" />

 

<

 

connectionStrings>

 

<

 

add name="ConnectionString" connectionString="Database=AppDataBlock;Server=localhost;Integrated Security=SSPI"

 

 

 

providerName="System.Data.SqlClient" />

 

</

 

connectionStrings>

 

</

 

configuration>


Custom database listener class :- 

 

using

 

System;

 

 

 

using

 

System.Collections.Generic;

 

 

 

using

 

System.Text;

 

 

 

using

 

System.Data.Common;

 

 

 

using

 

System.Data;

 

 

 

using

 

System.Diagnostics;

 

 

 

using

 

System.Collections.Specialized;

 

 

 

using

 

Microsoft.Practices.EnterpriseLibrary.Logging;

 

 

 

using

 

Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;

 

 

 

using

 

Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;

 

 

 

using

 

Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

 

 

 

using

 

Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;

 

 

 

using

 

Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;

 

 

 

using

 

Microsoft.Practices.EnterpriseLibrary.Data;

 

 

 

 

namespace

 

CustomLogger

 

{

[

ConfigurationElementType(typeof(CustomTraceListenerData))]

 

 

public class DatabaseCustomTraceListener : CustomTraceListener

 

 

 

 

{

 

public override void Write(string message)

 

{

 

throw new Exception("The method or operation is not implemented.");

 

}

 

public override void Write(Object o)

 

{

 

//LogEntry log = o as LogEntry;

 

 

 

 

 

CustLogEntry log = o as CustLogEntry;

 

 

Database db = DatabaseFactory.CreateDatabase();

 

 

DbCommand cmd = db.GetStoredProcCommand("WriteLog");

 

db.AddInParameter(cmd,

"eventID", DbType.Int32, log.EventId);

 

db.AddInParameter(cmd,

"priority", DbType.Int32, log.Priority);

 

db.AddParameter(cmd,

"severity", DbType.String, 32, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Severity.ToString());

 

db.AddParameter(cmd,

"title", DbType.String, 256, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Title);

 

db.AddInParameter(cmd,

"timestamp", DbType.DateTime, log.TimeStamp);

 

db.AddParameter(cmd,

"machineName", DbType.String, 32, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.MachineName);

 

db.AddParameter(cmd,

"AppDomainName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.AppDomainName);

 

db.AddParameter(cmd,

"ProcessID", DbType.String, 256, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ProcessId);

 

db.AddParameter(cmd,

"ProcessName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ProcessName);

 

db.AddParameter(cmd,

"ThreadName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ManagedThreadName);

 

db.AddParameter(cmd,

"Win32ThreadId", DbType.String, 128, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Win32ThreadId);

 

db.AddParameter(cmd,

"message", DbType.String, 1500, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Message);

 

db.AddInParameter(cmd,

"formattedmessage", DbType.String, log.Message);

 

 

//IDictionary<String, object> dictionary = log.ExtendedProperties;

 

 

 

 

 

//dictionary["UserName"].ToString();

 

 

 

 

db.AddInParameter(cmd,

"UserName", DbType.String, log.UserName);

 

db.AddOutParameter(cmd,

"LogId", DbType.Int32, 4);

 

db.ExecuteNonQuery(cmd);

 

int logId = Convert.ToInt32(cmd.Parameters[cmd.Parameters.Count - 1].Value);

 

}

 

public override void WriteLine(string message)

 

{

 

throw new Exception("The method or operation is not implemented.");

 

}

}

}

 

Custom Log Entry class :


 

using

 

System;

 

 

 

 

using

 

System.Collections.Generic;

 

 

 

 

using

 

System.Linq;

 

 

 

 

using

 

System.Text;

 

 

 

 

using

 

Microsoft.Practices.EnterpriseLibrary.Logging;

 

 

 

 

namespace

 

CustomLogger

 

{

 

public class CustLogEntry : LogEntry

 

{

 

public CustLogEntry()

 

:

base()

 

{

}

 

public string UserName { get; set; }

 

}

}

 

Form code where i call the logger component

 

 

private void Form1_Load(object sender, EventArgs e)

 

{

 

try

 

 

 

 

 

{

 

//LogEntry le = new LogEntry();

 

 

 

 

 

 

CustLogEntry le = new CustLogEntry();

 

le.TimeStamp = System.

DateTime.Now;

 

le.Categories.Add(

"Audit");

 

le.Categories.Add(

"ErrorMail");

 

le.Message =

"Testing our DB Logging";

 

le.EventId = 1234;

le.Title =

"Database Message";

 

le.Priority = 1;

le.UserName =

"test User";

 

 

Dictionary<string, Object> dict = new Dictionary<string, Object>();

 

dict.Add(

"UserName", "testing");

 

dict.Add(

"Testing Attr", "Attr");

 

le.ExtendedProperties = dict;

 

Logger.Write(le);

 

}

 

catch (LoggingException ex)

 

{

 

MessageBox.Show(ex.Message);

 

}

 

}


Apr 3, 2009 at 6:19 AM
Hi,
      Just a quick update. Some how i avoided that error. But strangely what happens when i execute Logger.Write(log) it gets into my custom listener class. But it never gets intot he method Write(object) instead it automatically gets into Write(String str) and Writeln(string str). Not sure why it is not entering the expected method. Please do let me know on this. In this below sample you can see the logic that inserts the values to db and other write and writeLine methods just throw an exception. I tried placing some hardcoded db statements inside these two methods and i saw the values getting inserted perfectly for this custom listener. But i want to get into the method that overrides write(object) to get the log information into DB. Any ideas why it is not getting there.

Regards,
Elango


using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;
using System.Diagnostics;
using System.Collections.Specialized;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Formatters;
using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ObjectBuilder;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
 

namespace CustomLogger
{
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class DatabaseCustomTraceListener : CustomTraceListener
{

public override void Write(string message)

{

throw new Exception("The method or operation is not implemented.");

}

public override void Write(Object o)
{

LogEntry log = o as LogEntry;

Database db = DatabaseFactory.CreateDatabase();

DbCommand cmd = db.GetStoredProcCommand("WriteLog");

 

db.AddInParameter(cmd,

"eventID", DbType.Int32, log.EventId);

 

db.AddInParameter(cmd,

"priority", DbType.Int32, log.Priority);

 

db.AddParameter(cmd,

"severity", DbType.String, 32, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Severity.ToString());

 

db.AddParameter(cmd,

"title", DbType.String, 256, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Title);

 

db.AddInParameter(cmd,

"timestamp", DbType.DateTime, log.TimeStamp);

 

db.AddParameter(cmd,

"machineName", DbType.String, 32, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.MachineName);

 

db.AddParameter(cmd,

"AppDomainName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.AppDomainName);

 

db.AddParameter(cmd,

"ProcessID", DbType.String, 256, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ProcessId);

 

db.AddParameter(cmd,

"ProcessName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ProcessName);

 

db.AddParameter(cmd,

"ThreadName", DbType.String, 512, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.ManagedThreadName);

 

db.AddParameter(cmd,

"Win32ThreadId", DbType.String, 128, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Win32ThreadId);

 

db.AddParameter(cmd,

"message", DbType.String, 1500, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Default, log.Message);

 

db.AddInParameter(cmd,

"formattedmessage", DbType.String, log.Message);

//IDictionary<String, object> dictionary = log.ExtendedProperties;

//dictionary["UserName"].ToString();

db.AddInParameter(cmd,

"UserName", DbType.String, log.UserName);

 

db.AddOutParameter(cmd,

"LogId", DbType.Int32, 4);

 

db.ExecuteNonQuery(cmd);

 

int logId = Convert.ToInt32(cmd.Parameters[cmd.Parameters.Count - 1].Value);

 

}

 

public override void WriteLine(string message)

 

{

 

throw new Exception("The method or operation is not implemented.");

 

}

}

}

 

Apr 3, 2009 at 8:35 AM

Override the TraceData method.

public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
}

You can check the data parameter, if it is a LogEntry, then call the Write(object) method.  

Just additional info, your assembly need not to be in GAC.  And if you want to add reference to assemblies that are in GAC, you can add reference to that assembly even from the bin/debug folder of the project where it is defined and just go to its properties, set Copy Local to False.  This tells Visual Studio that it is located in GAC. 


Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.
entlib.support@avanade.com

 


 

 

Apr 5, 2009 at 8:11 PM
Thanks Sarah. It works fine now. But i was thinking why i have to use TraceData. If i am rite when i override Write(object) it should get called directly based on signature. Please let me know if you have any suggestions on this.

Regards,
Elango
Apr 7, 2009 at 12:28 PM
Hi,

I dont really have a bright idea about why does it calls the traceData instead of the Write(object o). But I tried debugging it together with the source code, and In the LogSource.cs Line 160: there is a call <listener.TraceData(manager, Name, eventType, id, logEntry);> which eventually will call the TraceData method of your custom trace listener. If the TraceData method is not overriden by your custom trace listener, it will call the <Write(string message)> .

Valiant Dudan
Global Technology & Solutions
Avanade, Inc.
entlib.support@avanade.com