Skip to content

Codepolice

  • ⤫

Using log4net to Send Mail With SmtpAppender In a Console Application

Posted by Judy Alvarez Posted on February 28, 2022March 1, 2022
0

I recently built some console apps to do some testing on my server. I wanted to be able to run the apps and get them to print info to the console. I also wanted it to log to a text file and to send e-mails to me. Log4net was the perfect tool to get this done.

This is how my .config files look with log4net. Of course, you have to reference log4net and so on also, use NuGet!

<configuration>
<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.11.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />
</configSections>
[..]
<log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
      <file value="webcontent-logfile.txt" />
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message% - %level%newline" />
      </layout>
    </appender>
    <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender, log4net">
      <mapping>
        <level value="ERROR" />
        <foreColor value="Red, HighIntensity" />
      </mapping>
      <mapping>
        <level value="INFO" />
        <foreColor value="White" />
      </mapping>
      <mapping>
        <level value="DEBUG" />
        <foreColor value="Green" />
      </mapping>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level - %message% - %newline" />
      </layout>
    </appender>
    <appender name="EmailAppender" type="log4net.Appender.SmtpAppender">
      <!-- The SmtpAppender authenticates against the mail server, the buffersize of 10 provides 10 lines of context when an error happens. -->
      <subject value="Log: Web Content Server Report" />
      <to value="[email protected]" />
      <from value="[email protected]" />
      <smtpHost value="localhost" />
      <bufferSize value="100000" />
      <lossy value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%level - %message% - %newline" />
      </layout>
    </appender>
    <root>
      <appender-ref ref="FileAppender"/>
      <appender-ref ref="ColoredConsoleAppender"/>
      <appender-ref ref="EmailAppender"/>
    </root>
</log4net>
</configuration>

In the application, I just init log4net like this.

log4net.Config.XmlConfigurator.Configure();
ILog log = log4net.LogManager.GetLogger(typeof(Program));

I saw loads of examples where they used the “BasicConfigurator” instead of the “XmlConfigurator” for some reason but that did not work if I wanted to use the appenders specified in the .config files.

Anyway, since my console app is just running and then quits I had some problems with the SmtpAppender. I guessed I didn’t have time to send the mail before I exited the app but I found some code to solve this as well. Add this at the end of the app and you should be fine.

ILoggerRepository rep = LogManager.GetRepository();
foreach (IAppender appender in rep.GetAppenders()) {
    var buffered = appender as BufferingAppenderSkeleton;
    if (buffered != null) {
        buffered.Flush();
    }
}

Another trick is if you want to change the subject of the e-mail sent you can do like this.

ILoggerRepository rep = LogManager.GetRepository();
foreach (IAppender appender in rep.GetAppenders()) {
    if (appender is SmtpAppender) {
        ((SmtpAppender)appender).Subject = "Log: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm") +" Web Content Server Report";
    }
    var buffered = appender as BufferingAppenderSkeleton;
    if (buffered != null) {
        buffered.Flush();
    }
}

Sorry for not linking to the sources of all this code but most is just stolen from various Stack Overflow questions.

Categories: JavascriptTagged: application state in asp net, asp net 4.5, asp net and web development, asp net basics, asp net core documentation, asp net core latest version, asp net core tutorial for beginners, asp net curso, asp net development company india, asp net e commerce, asp net language, asp net logging, asp net page life cycle, asp net requiredfieldvalidator, asp net tutorial for beginners with examples, asp net tutorial pdf, asp net view state, asp net viewstate, asp net vs asp net mvc, asp net web service, asp net with angular, cross page posting in asp net, crystal report in asp net, message box in asp net, n tier architecture in asp net, page event in asp net, pdf asp net, range validator in asp net, uses of asp net, web api in asp net mvc

Post navigation

Previous Previous post: Send E-Mail When a task in Task Scheduler Fails
Next Next post: Request.Files is Empty in a Web Forms Application

Related Posts

  • Package efficiency and dependency hygiene

    #​752 — September 12, 2025 Read on the Web If you have any interest in music and being able to render music or generate music with JavaScript, be sure to check out the very end of this issue where we’ve dedicated an entire section to the topic 🙂__Your editor, Peter Cooper JavaScript Weekly How to Keep

    Posted by Posted on September 12, 2025
    0
  • A significant supply chain attack on the npm ecosystem

    #​592 — September 9, 2025 Read on the Web A Major Supply Chain Attack Hits the npm Ecosystem — In July, Socket warned us about a phishing campaign targeting npm package publishers. Sadly, a prolific package author (among others, like DuckDB, who explain how the attack worked on them) fell victim to the scam, resulting

    Posted by Posted on September 9, 2025
    0
  • Why browsers throttle JavaScript timers (and what to do about it)

    #​751 — September 5, 2025 Read on the Web JavaScript Weekly Mediabunny: A Complete Media Toolkit for JavaScript — Supporting both browsers and Node.js, this library lets you read, write and convert popular media file formats (e.g. MP4, MP3, and more) without needing to lean on dependencies like FFmpeg. You can make thumbnails, extract metadata,

    Posted by Posted on September 5, 2025
    0
  • The latest on Oracle’s hold on JavaScript

    #​750 — August 29, 2025 Read on the Web JavaScript Weekly An Illustrated Guide to Big O and Time Complexity — A fantastic JavaScript-oriented, interactive, visual essay about Big O notation and its role in describing algorithmic complexity. This is a beautiful bit of work, even if you’re already wise to O(log n) and O(n^2).

    Posted by Posted on August 29, 2025
    0
  • The productivity benefits from type stripping

    #​591 — August 26, 2025 Read on the Web How We Migrated Our Rush.js Monorepo to Node Type Stripping — Since v23.6 (and in LTS since v22.18.0), Node has supported running (most) TypeScript code by stripping the types out first. The Calm team was excited about the potential for improving productivity and DX, and set

    Posted by Posted on August 26, 2025
    0
  • We still love jQuery

    #​749 — August 22, 2025 Read on the Web ☀️ We’re back after a week off, though I’m starting to think we should have taken two weeks off as it’s been quite quiet in JavaScript-land this August! Nevertheless, we still have a full issue for you today, so let’s get on to it.. 😉__Peter Cooper, your

    Posted by Posted on August 22, 2025
    0
Judy Alvarez

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Codepolice

  • Github
  • Atlassian
  • Flatlogic
  • Xero
  • Jetbrains
  • Figma
  • Package efficiency and dependency hygiene
  • A significant supply chain attack on the npm ecosystem
  • Why browsers throttle JavaScript timers (and what to do about it)
  • The latest on Oracle’s hold on JavaScript
  • The productivity benefits from type stripping
https://flatlogic.com/generator
COPYRIGHT © 2025 - Codepolice