Click here to Skip to main content
16,015,559 members
Articles / Web Development / ASP.NET

AnLogger - ASP.NET Logger

Rate me:
Please Sign up or sign in to vote.
4.60/5 (11 votes)
13 Nov 2011CPOL5 min read 67.8K   1.6K   44   28
Easy and Fast ASP.NET Logging via Email and Storing Exception into File System as Files

Contents

  • Introduction
  • Overview of the AnLogger
    • ILogger
    • EmailLogger
    • FileLogger
    • ExceptionFormatter
    • EmailSender
    • ConfigurationReader
    • ConfigurationItems
    • MoreAboutTheError
  • Configuration
  • How to use AnLogger?
  • Test and Result
  • Limitations
  • History

Introduction

AnLogger is an ASP.NET logging library. The main task of this library is to log exception by sending exception details via email to the specified recipients or storing exception details into file system. It is simple, fast and easy to use library to log ASP.NET application exception. There are already many exception loggers for ASP.NET especially ELMAH but the difference between those and AnLogger it is really simple, easy to use and light weight ASP.NET exception logging library.

Overview of the AnLogger

AnLogger is a lightweight ASP.NET error logging library. It is extremely easy to use and easy to configure. Currently AnLogger support.

  • Log exception details by sending email.
  • Log exception details by saving into a file in the file system of the host server.

The usage of the AnLogger is easy, get the binaries of AnLogger, add as a reference to the web project and configure few things and call one of the loggers (EmailLogger or FileLogger) from AnLogger library.

AnLogger accepts an exception object as parameter, processes exception by formatting as HTML using standard .NET Framework Exception formatting function. The formatted data is either save into file system or send to the specified recipients via SmtpClient.

From the architecture point of view, AnLogger is a lightweight library. It currently has the following classes to log exception details:

ClassDiagram_AnLogger.png

Figure 1: Class diagram of the AnLogger library.

A brief description of the classes used by AnLogger:

ILogger

It is the interface definition of the AnLogger. This interface currently has the following three methods which will be implemented by all the Loggers used by AnLogger:

C#
namespace AnLogger
{
    using System;
    using System.Web;

    public interface ILogger
    {
        void Log(Exception exceptionDetails);
        void Log(Exception exceptionDetails, HttpRequest httpRequest);
        void Log(string formattedExceptionDetails);
    }
}

EmailLogger

It is responsible to log exception by sending exception details to the recipients via email. It uses standard .NET formatting function to format exception object into HTML formatted data and passes those data as message contents to the recipients specified in the configuration. EmailLogger is implemented as two overloaded methods with the following responsibility:

C#
namespace AnLogger
{
    using System;
    using System.Web;

    public class EmailLogger : ILogger
    {
        // To log exception details from Exception objects via Email.
        public void Log(Exception exceptionDetails)
        {
            EmailSender.SendExceptionDetails
        (ExceptionFormatter.GetHtmlFormmatedException(exceptionDetails), 
        exceptionDetails.Message);
        }

        public void Log(Exception exceptionDetails, HttpRequest httpRequest)
        {
            var formattedExceptionDetails = 
        ExceptionFormatter.GetHtmlFormmatedException(exceptionDetails);
            formattedExceptionDetails = formattedExceptionDetails.Replace
        ("", string.Concat(new MoreAboutTheError
            (httpRequest).ConstructTheSummary(), ""));
            EmailSender.SendExceptionDetails(formattedExceptionDetails, 
            exceptionDetails.Message);
        }

        // To log exception details from provided exception details data.
        public void Log(string formattedExceptionDetails)
        {
            EmailSender.SendExceptionDetails(formattedExceptionDetails);
        }
    }
}
  • Log(Exception exceptionDetails)
    • It accepts an exception object, processes it using built in .NET class named HttpUnhandledException and sends that processed data as email.
  • Log(string formattedExceptionDetails)
    • It accepts pre-formatted exception object data and sends that data as email.
  • Log(string formattedExceptionDetails, HttpRequest httpRequest)
    • It accepts pre-formatted exception object data and an object of current HttpRequest and sends that data as email.

FileLogger

It is responsible to log exception by writing formatted exception details to the file system. The default file path it will use by reading from the web.config appsettings.

C#
public class FileLogger : ILogger
    {
        // To log exception details from Exception object into file.
        public void Log(Exception exceptionDetails)
        {
            FileWriter.WriteToFile
        (ExceptionFormatter.GetHtmlFormmatedException(exceptionDetails));
        }

        public void Log(string formattedExceptionDetails)
        {
            FileWriter.WriteToFile(formattedExceptionDetails);
        }

        public void Log(Exception exceptionDetails, System.Web.HttpRequest httpRequest)
        {
            var formattedExceptionDetails = 
        ExceptionFormatter.GetHtmlFormmatedException(exceptionDetails);
            FileWriter.WriteToFile(formattedExceptionDetails.Replace
        ("", string.Concat(new MoreAboutTheError
            (httpRequest).ConstructTheSummary(), "")));
        }
    }

EmailLogger and FileLogger are the core classes of the AnLogger library, there are other classes used such as:

ExceptionFormatter

This class is responsible to format .NET Exception object into HTML formatted data using built in .NET functionality:

C#
namespace AnLogger
{
    using System;
    using System.Web;

    internal static class ExceptionFormatter
    {
        // It will format the exception message and stack trace from 
        // exception object into formatted HTML code.
        internal static string GetHtmlFormmatedException(Exception exceptionToFormat)
        {
            HttpUnhandledException httpUnhandledException = 
          new HttpUnhandledException(exceptionToFormat.Message, exceptionToFormat);
            return httpUnhandledException.GetHtmlErrorMessage();
        }
    }
}

From the above code, HttpUnhandledException is the class used to format the exception object into HTML formatted data.

EmailSender

This is responsible to send email using SmtpClient. To be able to send email by AnLogger, web.config has to have a few values into configuration file. It has been discussed broadly into Configuration section of this article.

ConfigurationReader

To read config entry from the configuration file such as web.config.

ConfigurationItems

This enum contains all the configuration item used by AnLogger to configure itself as values. So enum will used by different classes for example, EmailSender or FileWriter class to read configuration entry.

C#
enum ConfigurationItems
{
     To = 0,
     From,
     SmtpServer,
     DefaultFilePath,
}

So there will be also four config entries in appsettings section of the web.config file.

Configuration

There are currently four different configuration items (DefaultFilePath, To, From, SmtpServer) used in AnLogger. All these items are related to E-mail address, Smtp server address, etc.

XML
 <appsettings>   
      <add key="DefaultFilePath" value="default path name to store file">
      <add key="To" value="username@domainname">
      <add key="From" value="username@domainname">
      <add key="SmtpServer" value="smtp server address">
</add></add></add></add>
</appsettings>

All of those configuration entries have been used for different purposes, for example, to get to E-mail address, Smtp server address, etc. The following table describes those entries:

Configuration itemDescription
DefaultFilePath It will define the location of the file path, where FileLogger will store file with exception details as contents. The following example will show how to define DefaultFilePath into web.config:
XML
<add key="DefaultFilePath" 
    value="default path name to store file" />
To It will contain the to address to send the email.
XML
<add key="To" value="username@domainname" />
From It will contain the From address.
XML
<add key="From" value="username@domainname" />
SmtpServer The name of the Smtp server address.
XML
<add key="SmtpServer" value="smtp server address" />
Figure 2: Description of the Configuration entries used by AnLogger

MoreAboutTheError

C#
namespace AnLogger
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.UI;

    public class MoreAboutTheError
    {
        private string host;
        private string url;
        private string date;
        private string time;
        private string requestTypes;
        private string totalBytes;
        private string cookies;
        private string browserDetails;
        private string headerDetails;
        private const string LineBreak = "<br/>";

        public MoreAboutTheError(HttpRequest request)
        {
            host = request.Url.Host;
            url = request.Url.AbsoluteUri;
            date = DateTime.Now.Date.ToShortDateString();
            time = DateTime.Now.ToShortTimeString();
            headerDetails = HeaderDetails(request);
            requestTypes = request.RequestType;
            totalBytes = request.TotalBytes.ToString() + "bytes";
            browserDetails = GetBrowserDetails(request);
            cookies = GetCookieDetails(request);
        }
        public string ConstructTheSummary()
        {
            //Code has been removed for simplicity
        }
        private void AddCellContents(HtmlTextWriter writer, string contents)
        {
            //Code has been removed for simplicity
        }
        private static void AddCellHeader(HtmlTextWriter writer, 
        string dataToWrite, string textAlign = "Right")
        {
            //Code has been removed for simplicity
        }
        private string HeaderDetails(HttpRequest request)
        {
            //Code has been removed for simplicity
        }
        private string GetBrowserDetails(HttpRequest request)
        {
            //Code has been removed for simplicity
        }
        private string FormateWithLineBreak(string item1, string item2)
        {
            return string.Format("{0} :  {1} {2}", item1, item2, LineBreak);
        }
        private string GetCookieDetails(HttpRequest request)
        {
            //Code has been removed for simplicity
        }
    }
}

This class is responsible to format Advanced error details, for example, host address, URL, Request Headers information. This class extracts all the related information from a given object of type HttpRequest.

How to Use AnLogger?

It is only three steps to use AnLogger to an ASP.NET application:

  • Get the AnLogger binary and add as Reference to the ASP.NET project.
  • Configure the web.config file to add configuration entry.
  • Call one of the Loggers (EmailLogger or FileLogger) from Global.asax.cs file.

The following image shows the steps how to use AnLogger:

Usage_Of_AnLogger_V2.png
Figure 3: How to use AnLogger with an Asp.Net application

From the above image, AnLogger.dll has been added to the AnLoggerTestHarness project, in the web.config of the AnLoggerTestHarness project added related configuration entry and finally from the Global.asax.cs file one of the loggers (EmailLogger) has been called to log Exception by sending email with exception details as its contents.

If decided to use FileLogger then To, From and SmtpServer configuration entries do not require to configure because all of these entries are related to the EmailLogger functionality. Only configuration entry required is DefaultFilePath. The usage of the FileLogger from Global.asax.cs file is as below:

C#
void Application_Error(object sender, EventArgs e)
{
     // Code that runs when an unhandled error occurs
     FileLogger fileLogger = new FileLogger();
     fileLogger.Log(Server.GetLastError(),Request);
}

Test and Result

The following diagram shows an ASP.NET which uses AnLogger to log exception and sends the HTML formatted exception to the recipients via Email.

TestHarnessAtRuntime.png

Email_Output.png

Figure 4: Test usage of the AnLogger

The email body contains the HTML formatted exception raised by Online Calculator program and handled by AnLogger.

Limitations

The following limitations exist in this release of AnLogger:

  • It does not contain any HTTPModules to log exception.

History

  • Version 1
  • Version 2

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Australia Australia

Comments and Discussions

 
SuggestionLog4Net comparison Pin
Reiss9-Oct-11 22:52
professionalReiss9-Oct-11 22:52 
GeneralRe: Log4Net comparison Pin
Mohammad A Rahman9-Oct-11 23:05
Mohammad A Rahman9-Oct-11 23:05 
GeneralRe: Log4Net comparison Pin
kiquenet.com1-Nov-11 21:45
professionalkiquenet.com1-Nov-11 21:45 
GeneralRe: Log4Net comparison Pin
Mohammad A Rahman1-Nov-11 23:37
Mohammad A Rahman1-Nov-11 23:37 
GeneralRe: Log4Net comparison Pin
kiquenet.com21-Nov-11 20:53
professionalkiquenet.com21-Nov-11 20:53 
QuestionNice Article very helpful Pin
_Tushar Patil9-Oct-11 22:16
_Tushar Patil9-Oct-11 22:16 
AnswerRe: Nice Article very helpful Pin
Mohammad A Rahman9-Oct-11 22:18
Mohammad A Rahman9-Oct-11 22:18 
QuestionDownload Link broken...Please Check Pin
_Tushar Patil9-Oct-11 20:08
_Tushar Patil9-Oct-11 20:08 
Download Link broken...Please Check
AnswerRe: Download Link broken...Please Check Pin
Mohammad A Rahman9-Oct-11 21:17
Mohammad A Rahman9-Oct-11 21:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.