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

  • TypeScript and JavaScript dominate on GitHub in 2025

    #​759 — October 31, 2025 Read on the Web JavaScript Weekly Directives and the Platform Boundary — First there was the “use strict” directive to opt in to strict mode in JavaScript, but now you’ll encounter use client, use server, React’s new use no memo, and more, and they’re not standard JS features at all.

    Posted by Posted on October 31, 2025
    0
  • The reality of porting Deno code to Node

    #​598 — October 28, 2025 Read on the Web Awesome Node: Over 500 Curated Packages, Resources and Links — It’s been more than four years since we linked to Sindre’s handy resource, but it continues to get updates and tweaks (and, if you want, you can contribute a submission too – though the bar is

    Posted by Posted on October 28, 2025
    0
  • Vitest 4.0 and Next.js 16

    #​758 — October 24, 2025 Read on the Web JavaScript Weekly Vitest 4.0 Released: The Vite-Native Testing Framework — The Vite-powered, Jest-compatible testing framework introduces visual regression testing, makes its ‘Browser Mode’ stable (for running tests in a browser directly), adds Playwright Traces support, and more. Still unsure? You can compare it with other test

    Posted by Posted on October 24, 2025
    0
  • Node.js 25.0 arrives

    #​597 — October 21, 2025 Read on the Web Node.js v25.0.0 (Current) Released — The latest cutting edge version of Node has arrived with Web Storage enabled by default, JSON.stringify perf improvements, a new –allow-net option in the permission model, built-in Uint8Array base64/hex conversion, and WebAssembly and JIT optimizations. As shown in the diagram above, this

    Posted by Posted on October 21, 2025
    0
  • A Bun-believable release that isn’t half-baked

    #​757 — October 17, 2025 Read on the Web JavaScript Weekly Bun 1.3: The Full-Stack JavaScript Runtime — Arriving a few hours after last week’s issue (natch!) Bun 1.3 remains the big news of the past week. Bun is a performance and DX-focused JavaScriptCore-powered runtime which, with v1.3, balances being a drop-in Node.js replacement with

    Posted by Posted on October 17, 2025
    0
  • Bringing Python apps into Node

    #​596 — October 14, 2025 Read on the Web 📂 A Modern Guide to Reading and Writing Files in Node — A comprehensive guide to various methods for working with files, from promise-based methods through to working with streams, processing files concurrently, using file handles, and memory-efficient techniques. Luciano Mammino A Way to Integrate Python ASGI with Node.js

    Posted by Posted on October 14, 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
  • TypeScript and JavaScript dominate on GitHub in 2025
  • The reality of porting Deno code to Node
  • Vitest 4.0 and Next.js 16
  • Node.js 25.0 arrives
  • A Bun-believable release that isn’t half-baked
https://flatlogic.com/generator
COPYRIGHT © 2025 - Codepolice