5,666,979 members and growing! (17,165 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Utilities     Intermediate License: The Code Project Open License (CPOL)

A log4net Realtime Color Console for ASP.NET

By Philip Liebscher

An article on how to create a real-time log4net color console viewer for ASP.NET applications.
Windows, .NET, Visual Studio, ASP.NET, Dev

Posted: 26 Jan 2007
Updated: 26 Jan 2007
Views: 18,291
Bookmarked: 31 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
10 votes for this Article.
Popularity: 4.76 Rating: 4.76 out of 5
0 votes, 0.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
2 votes, 20.0%
4
8 votes, 80.0%
5

AspLog4netColorConsole.jpg

Introduction

I was getting close to deploying a new Asp.Net web application and needed a good, solid logger. I had written my own simple logger when I started the project, but it just wasn't very clean, easy to manage or configurable. I'd seen many references to log4net  scattered about and decided to check it out. And; I'm glad I did. In a few hours I was up and running. It was a bit difficult at first as there are so many different ways to use it and a lot of documentation (a good thing). Finding to correct configuration took a little effort, but was well worth it.

If you're new to log4net, you may want to start here: A Brief Introduction to the log4net logging library, using C#. There are quite a few other great articles surrounding log4net on the Code Project. Just do a search and you'll find many.

After setting up a few basic file and email loggers I start looking at all the other loggers (a.k.a Appenders) that log4net offered. I thought it would be great to have a real time console showing me what was happening after the application was deployed. The Udp logger seemed interesting, but I didn't know enough about log4net to imagine how I could use it. So I searched around a bit to see if anyone had any example uses. I came across the Log4NetViewer. It's a simple WinForm app that receives log4net messages sent from the UdpAppender. Pretty neat, eh. Now I could remotely monitor my web applications. So I set it up and used it for a while in my dev environment. It worked well, but I really didn't like the way it displayed the log messages. It uses a grid to display the log. A new row is appended to the grid when a new log message is received. The problem though, is that long messages, like exceptions, are hard to read. You either had to scroll through the cell or copy/paste the message. Even worse, no source code! Anyway, I let the subject rest and moved on to more important tasks.

A while later, while making some configuration changes to my log4net setup, I came across the ConsoleAppender and, the even better, ColoredConsoleAppender. Who doesn't love color. Maybe I could monitor my web app's log messages in a log4net console window? The messages would be easy to read and could even be color coded. I started digging around for some samples and realized that the console loggers cannot directly work with Asp.net applications. There really is no console in log4net. No console will magicly pop-up when you add the ConsoleAppender to your log4net configuration. A console would need to run in the same process or context as the Asp application. It cannot, but does it really need to?

No. Of course not...

Ah Ha! I recalled the UdpAppender. I could create a .net console application and use the System.Net.Sockets.UdpClient to listen for Udp log message sent from my Asp.net application. Just like the Log4NetViewer. Then use the ColoredConsoleAppender to write them to the console window. A couple hours later... Presto.

Using the code

The code for the console app is pretty simple:

' Create a console app and add a reference to log4net.

' Add this global attribute. Generally it should go in the AssemblyInfo.vb file.

<Assembly: log4net.Config.XmlConfigurator(Watch:=True)>

Imports System.Net.Sockets
Imports System.Net
Module UdpLogListener
    Private ReadOnly Log As log4net.ILog = _
     log4net.LogManager.GetLogger( _
     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

Sub Main()

    ' Remember to use the same port in your web/source app.

    Dim Port As Integer = 8081
    
    Dim Sender As IPEndPoint
    Dim Client As UdpClient
    Dim Buffer As Byte()
    Dim LogLine As String

    Try
        Sender = New IPEndPoint(IPAddress.Any, 0)
        Client = New UdpClient(Port)

        While True
            Buffer = Client.Receive(Sender)
            LogLine = System.Text.Encoding.Default.GetString(Buffer)
            ' The color-coded text is written to the console

            ' when Log.{level method} is called.

            ' i.e. Log.Info("my info")

            ' Optional: Replace your placeholders with whatever

            ' you like. [I]=Info, [D]=Debug, etc.

            '            More detail about placeholders in the

            '           UdpAppender config below.

            If LogLine.IndexOf("{INFO}") >= 0 Then
                Log.Info(LogLine.Replace("{INFO}", "[I] "))
            ElseIf LogLine.IndexOf("{DEBUG}") >= 0 Then
                Log.Debug(LogLine.Replace("{DEBUG}", "[D] "))
            ElseIf LogLine.IndexOf("{ERROR}") >= 0 Then
                Log.Error(LogLine.Replace("{ERROR}", "[E] "))
            ElseIf LogLine.IndexOf("{WARN}") >= 0 Then
                Log.Warn(LogLine.Replace("{WARN}", "[W] "))
            Else
                ' Some other level.

                Log.Warn(LogLine)
            End If
        End While

    Catch e As Exception
        Console.WriteLine(e)
        Console.WriteLine(vbCrLf & _
                "Press any key to close...")
        Console.ReadLine()
    End Try

End Sub
End Module

Configure the ColoredConsoleAppender and set the log-level colors. The following goes in your App.config :

<configSections>
    <section name="log4net" 
            type="System.Configuration.IgnoreSectionHandler" />
</configSections>
<log4net>
    <appender name="ColoredConsoleAppender" 
        type="log4net.Appender.ColoredConsoleAppender">
        <mapping>
            <level value="INFO" />
            <foreColor value="White, HighIntensity" />
            <backColor value="Green" />
        </mapping>
        <mapping>
            <level value="DEBUG" />
            <foreColor value="White, HighIntensity" />
            <backColor value="Blue" />
        </mapping>
        <mapping>
            <level value="WARN" />
            <foreColor value="Yellow, HighIntensity" />
            <backColor value="Purple" />
        </mapping>
        <mapping>
            <level value="ERROR" />
            <foreColor value="Yellow, HighIntensity" />
            <backColor value="Red" />
        </mapping>
        <layout 
                    type="log4net.Layout.PatternLayout">
            <conversionPattern value="%message%newline" />
        </layout>
    </appender>
    <root>
        <level value="ALL" />
        <appender-ref ref="ColoredConsoleAppender" />
    </root>
</log4net>

Lastly, in your ASP.Net application, Configure a source UdpAppender to send Udp log messages to your console. Add the following to your log4net config file (see sample application for full config. There a several ways to configure log4net. If you're using a different method, you'll only need the <appender...> section below and an <appender-ref ref="UdpAppender"> in your root .) Remember to match the RemotePort with the UdpClient port in your console app. Also note that you can format the pattern layout however you like and even add delimiters and place holder that can be parsed by the client. Below, the {%level} value is replaced in the main loop before being written to the screen. Additional information on PatternLayout syntax can be found in the log4net SDK PatternLayout Class. Note that the layout conversionPattern above (in the console's App.config) has no pattern formatting. The formatting should be set at the source UdpAppender pattern layout config. I'm sure you can use other layout types as well. There are quite a few.

<log4net>
    <appender name="UdpAppender" type="log4net.Appender.UdpAppender">
        <param name="RemoteAddress" value="localhost" />
        <param name="RemotePort"
            value="8081" />
        <layout type="log4net.Layout.PatternLayout" 
            value="{%level}%date{MM/dd HH:mm:ss} - %message" />
    </appender>
    <root>
        <level value="ALL" />
        <appender-ref ref="UdpAppender" />
    </root>
</log4net>

Points of Interest

The UdpAppender gives great flexability in bridging remote log viewers and writers. Like the Log4NetViewer, WinForm clients can be created as well as Console clients as seen here. Even remote file loggers. You simply need a Udp client and log4net to broadcast, capture and rewrite log messages. Also, the source UdpAppender can be configured to broadcast the log messages to the entire subnet. This allows you to setup multiple client loggers in multiple locations Doing multiple things.

On the flip side, the Udp protocol is meant only to broadcast, there is no validation between the sender and receiver. So there is no guarantee that messages will be received or even received in the same order as sent. But that's ok with me, the RollingFileAppender doesn't miss anything.

I hope you enjoyed. This is my first article post so I thought I would keep the topic simple... I think.

History

01-26-2007     Initial Creation.

 

License

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

About the Author

Philip Liebscher



Occupation: Web Developer
Location: United States United States

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 9 of 9 (Total in Forum: 9) (Refresh)FirstPrevNext
GeneralHow did I miss this?memberGrimaceOfDespair5:50 12 Feb '08  
QuestionCannot get logs from a remote computermemberMattPenner12:58 1 Mar '07  
AnswerRe: Cannot get logs from a remote computermemberPhil Liebscher5:53 2 Mar '07  
GeneralAny performance issue on IIS server?membertops17:56 4 Feb '07  
GeneralRe: Any performance issue on IIS server?memberPhil Liebscher6:55 5 Feb '07  
GeneralAny security issues? [modified]memberjoebeam18:20 26 Jan '07  
AnswerRe: Any security issues?memberpliebscher18:49 26 Jan '07  
GeneralHaven't run the code but I will...supportercode-frog14:43 26 Jan '07  
GeneralRe: Haven't run the code but I will...memberpliebscher18:33 28 Jan '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 26 Jan 2007
Editor: Smitha Vijayan
Copyright 2007 by Philip Liebscher
Everything else Copyright © CodeProject, 1999-2008
Web09 | Advertise on the Code Project