Click here to Skip to main content
13,252,815 members (50,219 online)
Click here to Skip to main content
Add your own
alternative version


13 bookmarked
Posted 24 Oct 2013

Simplest Workable Logging and Emailing of Messages from ASP.NET using Log4Net

, 25 Oct 2013
Rate this:
Please Sign up or sign in to vote.
Steps to add logging to files and emailing from ASP.NET apps


When something goes wrong "in the field," the users oftentimes have no clue how to describe it; their explanations tend to be quite vague, such as simply, "it doesn't work."

An aid for developers to be proactive and get more specific information about errors thrown by their software is to email details of such to themselves. The FOSS package Log4Net makes this pretty simple. Here is the easiest possible way (that I know of) to set up Log4Net emailing of error messages in an ASP.NET app:

Note: Instructions apply to Visual Studio 2013; other versions may differ a little (the older the version, the more they would possibly diverge.)

Steps for Installing and Using Log4Net

  1. Download and install Log4Net into your project via NuGet (Tools > Library Package Manager > Manage NuGet Packages for Solution... > Online, search for "log4net" > Install).
  2. Add this to Web.config below/within the <configuration> section:
  3. <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
        <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
          <param name="File" value="HandheldServer.log"/>
          <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
          <appendToFile value="true" />
          <rollingStyle value="Size" />
          <maxSizeRollBackups value="2" />
          <maximumFileSize value="1MB" />
          <staticLogFileName value="true" />
          <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
        <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender,log4net">
          <threshold value="ERROR" />
          <to value="" />
          <from value="" />
          <subject value="log4net err msg - My ASP.NET app" />
          <smtpHost value="" />
          <port value="587"/>
          <authentication value="Basic" />
          <username value=""/>
          <password value="kennwort42"/>
          <EnableSsl value="true" />
          <bufferSize value="1" />
          <lossy value="true" />
          <layout type="log4net.Layout.PatternLayout,log4net">
            <conversionPattern value="%property{log4net:HostName} :: %level :: %message 
              %newlineLogger: %logger%newlineThread: %thread%newlineDate: 
              %date%newlineNDC: %property{NDC}%newline%newline" />
          <level value="INFO"/>
          <appender-ref ref="LogFileAppender" />
          <appender-ref ref="SmtpAppender" />

    Note that many/most of the entries in the "SmtpAppender" <appender> section can be changed, and in fact you will need to change the following values to those that are appropriate for you:

    <to value="" />
    <from value="" />
    <smtpHost value="" />
    <port value="587"/>
    <username value=""/>
    <password value="kennwort42"/> 
  4. Append this to AssemblyInfo.cs:
    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]   
  5. In each class where you want to use Log4Net, add this (Intellisense should help you add the required using clauses):
    private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); 
  6. In the classes where you've performed step 3, call one of Log4Net's methods, such as Error:
    log.Error("es klappt einfach nicht"); 

    For example, you might do this in a catch block:

    catch (Exception ex)
  7. Test that Log4Net is working by temporarily wreaking some sort of mayhem (in your debug environment, of course), such as deliberately dividing by zero:
        int i = 0;
        int j = 1 / i;
    catch (Exception ex)

When you run this code with the setup above, you will both get an error message logged to a file in your project's folder named <MyProject>.log with content similar to this:

2013-10-24 09:57:12,348 [9] ERROR <MyProject>.<subfolder>.<methodName> Attempted to divide by zero.

...and you will receive an email with content similar to this:

<computerName> :: ERROR :: Attempted to divide by zero. 
Logger: <MyProject>.<subfolder>.<methodName>
Thread: 7
Date: 2013-10-24 09:53:14,717
NDC: (null)


By using this tip, you may be able to discover and fix exceptions thrown in your ASP.NET app before users even get a chance to report them. At the very least, it arms you with more actionable information than the vague, "It's broke" that users are wont to proffer.

Even when testing apps in the dev environment, logging errors can be very enlightening, leading to more efficient debugging; as an example, yesterday when I was testing a Web API server / Winforms client pair of apps, an error dialog displayed in my client app due to an exception on the server. The vague message being shown was "The remote server returned an error: (405) Method Not Allowed."

When I looked at the log file created by Log4Net for my server app, it gave me more specific/useful info, namely "Specified cast is not valid" - that tells me a  lot more than the other message, which basically said, "it's not working."  


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


About the Author

B. Clay Shannon
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006:

You may also be interested in...


Comments and Discussions

QuestionIt worked for me Pin
DineshShrinath2-Jul-14 3:32
memberDineshShrinath2-Jul-14 3:32 
QuestionDemo Pin
Member 1052339210-Apr-14 6:42
memberMember 1052339210-Apr-14 6:42 
AnswerRe: Demo Pin
B. Clay "el Gonző" Shannon10-Apr-14 7:11
professionalB. Clay "el Gonző" Shannon10-Apr-14 7:11 
GeneralRe: Demo Pin
Member 1052339210-Apr-14 7:17
memberMember 1052339210-Apr-14 7:17 
GeneralRe: Demo Pin
B. Clay "el Gonző" Shannon10-Apr-14 7:28
professionalB. Clay "el Gonző" Shannon10-Apr-14 7:28 
GeneralRe: Demo Pin
Member 1052339210-Apr-14 7:34
memberMember 1052339210-Apr-14 7:34 
GeneralRe: Demo Pin
B. Clay "el Gonző" Shannon10-Apr-14 7:40
professionalB. Clay "el Gonző" Shannon10-Apr-14 7:40 
QuestionDidnt work off the bat Pin
chardog14-Nov-13 20:00
memberchardog14-Nov-13 20:00 
AnswerRe: Didnt work off the bat Pin
Member 1052339210-Apr-14 7:38
memberMember 1052339210-Apr-14 7:38 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171114.1 | Last Updated 25 Oct 2013
Article Copyright 2013 by B. Clay Shannon
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid