Loupe - Log - Monitor - Resolve
Loupe / Developer's Guide / For .NET Framework / For ASP.NET MVC / Submitting Sessions on Error / Developer's Guide - Log Message Alerting
In This Topic
    Developer's Guide - Log Message Alerting
    In This Topic

    Once you begin routing your logging into Loupe, it's natural to want to be able to respond to log events.  By using the MessageAlert event you can take action when a critical, error, or warning message is logged regardless of source - whether generated internally by Loupe or logged by your own code.  Additionally, there are several safety enhancements built into this event to make it easy to focus just on the actions you want to take:

    The Message Alert event is particularly useful for automatically triggering immediate data transmission in the case of an error or implementing your own error notification mechanism.  The full detail of each log message is available in the event.

    When Auto Send Sessions is enabled sessions are automatically sent after this event is raised unless the Auto Send On Error option is set to false or you override the SendSession value.

    Scenario One:  Generate an email alert when an error occurs

    When you want to provide proactive support it often isn't sufficient to simply submit the data to the Loupe Server, it's useful to send an email to a fast response address with information about the problem so you can decide whether it's necessary to interrupt your other work and research this new issue.

    This example also demonstrates how to process the full log message information available during the MessageAlert event to compose messages or perform more advanced processing.  Finally, it utilizes the SendMessage Method method to send the email, allowing you to leverage your existing Agent configuration for email server, from, and to address (which must be configured for this example to work)

    Send an email when an error is reported
    Copy Code
    using System;
    using System.Collections.Generic;
    using System.Net.Mail;
    using System.Text;
    using System.Threading;
    using Gibraltar.Agent.Data;
    
    private void Log_MessageAlertSendEmail(object sender, LogMessageAlertEventArgs e)
    {
        //if we had an error or critical we want to send
        if (e.TopSeverity <= LogMessageSeverity.Error) //numeric values DROP for more severe enum values
        {
            //get the set of messages that are the "worst" in this event.
            List<ILogMessage> badMessages = new List<ILogMessage>();
            foreach (ILogMessage message in e.Messages)
            {
                if (message.Severity == e.TopSeverity)
                {
                    badMessages.Add(message);
                }
            }
            //now make us an email message describing these guys
            string messageBody = FormatMessageBody(badMessages);
            string subject = string.Format("{0} {1}: {2}", Log.SessionSummary.Application,
                e.TopSeverity.ToString().ToUpper(), badMessages[0].Caption);
            //and for safety's sake lets keep our subject from being crazy long.
            if (subject.Length > 120)
            {
                subject = subject.Substring(0, 120) + "...";
            }
            //now that we've done all of that, lets send our message using the Agent's email config
            using (MailMessage message = new MailMessage())
            {
                message.Subject = subject;
                message.Body = messageBody;
                message.Priority = MailPriority.High;
                //now send our email!  I'm not bothering to catch exceptions since the Agent handles that nicely for us
                Log.SendMessage(message); //synchronous OK because we're already async from the flow of logging.
            }
            //and lets make sure we don't send again for at least a few minutes
            //to ensure we don't flood in the event of a storm of errors.
            e.MinimumDelay = new TimeSpan(0, 5, 0); //5 minutes
        }
    }
    
    private string FormatMessageBody(List<ILogMessage> messages)
    {
        StringBuilder messageBody = new StringBuilder(1024);
        //we write out more detail about the first item, then just summarize.
        ILogMessage firstMessage = messages[0];
        messageBody.AppendFormat("Timestamp: {0:g}\r\n", firstMessage.Timestamp);
        messageBody.AppendFormat("Category:  {0}\r\n", firstMessage.CategoryName);
        messageBody.AppendFormat("Class:     {0}\r\n------------------------------\r\n", firstMessage.ClassName);
        messageBody.AppendFormat("{0}\r\n", firstMessage.Caption);
        messageBody.AppendFormat("{0}\r\n\r\n", firstMessage.Description);
        //report any exceptions on this first object.
        IExceptionInfo currentException = firstMessage.Exception;
        if (currentException != null)
        {
            messageBody.Append("Exceptions:\r\n");
            while (currentException != null)
            {
                messageBody.AppendFormat("{0}: {1}\r\n\r\n", currentException.TypeName, currentException.Message);
                //Each outer exception can point to an inner exception, we get null when there are no more.
                currentException = currentException.InnerException;
            }
        }
        //summarize the rest of the messages
        if (messages.Count > 1)
        {
            messageBody.AppendFormat("Other {0}s:\r\n", firstMessage.Severity);
            for (int curMessageIndex = 1; curMessageIndex < messages.Count; curMessageIndex++)
            {
                ILogMessage currentMessage = messages[curMessageIndex];
                messageBody.AppendFormat("------------------------------\r\nMessage {0} of {1}: {2}: {3}\r\n\r\n",
                    curMessageIndex, messages.Count, currentMessage.Severity, currentMessage.Caption);
            }
        }
        return messageBody.ToString();
    }
    

     

    See Also