WCF Custom trace listener to write logs in msmq without EnterpriseLibrary

833 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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>
1
On

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.