wcftracelistenertrace-listener

WCF Custom trace listener to write logs in msmq without EnterpriseLibrary


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


Solution

  • 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>