Rohit Sonaje
Rohit Sonaje

Reputation: 532

WCF Custom trace listener to write logs in msmq without EnterpriseLibrary

How to write custom trace listener to write message logs in msmq?

Upvotes: 0

Views: 857

Answers (2)

Rohit Sonaje
Rohit Sonaje

Reputation: 532

I have added below custom MSMQTraceListener :

public class MSMQTraceListener : TraceListener
{
    string _queueName; 

    public MSMQTraceListener(string queueName)
        : base("MSMQListener")
    {
        _queueName = queueName;
        if (!MessageQueue.Exists(_queueName))
            MessageQueue.Create(_queueName);
    }


    public override void Write(string message)
    {
        SendMessageToQueue(message);
    }

    public override void WriteLine(string message)
    {
        SendMessageToQueue(message);
    }

    /// <summary>
    /// Send message to queue.
    /// </summary>
    /// <param name="message">string: message</param>
    private void SendMessageToQueue(string message)
    {
        try
        {
            MessageQueue messageQueue = new MessageQueue(_queueName, QueueAccessMode.Send);
            messageQueue.Label = DateTime.Now.ToString();
            messageQueue.Send(message);
            messageQueue.Close();
        }
        catch (Exception ex)
        {

        }
    }
}

And updated below diagnostic setting in my web.config file:

<system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
          <add name="messages" type="Proj.Common.Diagnostics.MSMQTraceListener,Proj.Common" initializeData=".\private$\PerformanceTesting" />
        </listeners>
      </source>
    </sources>
</system.diagnostics>

Upvotes: 1

MatthewMartin
MatthewMartin

Reputation: 33183

If you are in code hosted by MSMQ and want to write a message to say a log file All .NET applications are the same as far as System.Diagnostics is concerned. Configure the listener in app.config, and use Trace or TraceSource to write to the listener. MSDN explains this better than I can.

If you want a trace listener that sends message to MSMSQ Get this utility library, Essential Diagnostics, that makes working with System.Diagnostics less painful

Override the one TraceEvent() method on BaseTraceListener. Inside that method, you use the available parameters to send messages to whatever you'd like, for example an MSMQ destination.

Register your custom TraceListener in the usual way.

Upvotes: 0

Related Questions