Click here to Skip to main content
13,898,644 members
Click here to Skip to main content
Add your own
alternative version


9 bookmarked
Posted 23 Jan 2012
Licenced CPOL

log4net: Log to a JavaScript Console

, 23 Jan 2012
Rate this:
Please Sign up or sign in to vote.
A new appender for the log4net logging tool that sends server logging strings to a JavaScript console.

While lurking and skulking in the shadows of various technical .NET sites, I've noticed many developers discussing log4net in their blogs and posts; log4net is an extremely popular tool for logging .Net Applications. So, I decided to try it out. After the initial complexities of getting it up and running, I was suitably impressed. Could it be…logging is fun? Well, I don't know if I'd go that far… at least I'd never admit it.

One of the great features of log4net is how easy it is to route the logs to multiple outputs. Here is an incomplete list of outputs… or 'Appenders' in the log4net vernacular:

AdoNetAppenderLogs to databases
ConsoleAppenderLogs to a console window
EventLogAppenderLogs to Windows event log
FileAppenderLogs to a file
RollingFileAppenderLogs to multiple files
SmtpAppenderLogs to an email address
TraceAppenderLogs to the .NET trace system
AspNetTraceAppenderLogs to the ASP.NET page trace
MemoryAppenderLogs to a memory buffer
Etc., etc., etc.


I've been doing a lot of work with jQuery/JavaScript and it dawned on me that seeing server side logging strings in a JavaScript Console could be useful.

So I wrote a log4net JavaScript Console Appender. Strings logged at the server will show up in the browser's console window. Note: For IE, you need to have the "Developer Tools" window active.

I'm not going to describe how to setup log4net in an ASP.NET web site; there are many step-by-step tutorials around. But I'll give you some hints:

  • Each step must be followed or it will not work (duh).
  • Putting the log4net settings in a separate configuration file is more complicated than having the settings in web.config: Start with the settings in web.config.
  • The name in this line of code: LogManager.GetLogger("MyLogger"); ... refers to this section in the configuration file: <logger name="MyLogger">.

I built the Appender and a test ASP.NET site in .NET Framework 4.0. Here's the jsConsoleAppender.cs file:

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Core;
using log4net.Appender;
using log4net.Layout;
using System.Web;
using System.Web.UI;
namespace log4net.Appender
    // log4net JSConsoleAppender
    // Writes log strings to client's javascript console if available
    public class JSConsoleAppender : AppenderSkeleton
        // each JavaScript emitted requires a unique id, this counter provides it
        private int m_IDCounter = 0;
        // what to do if no HttpContext is found
        private bool m_ExceptionOnNoHttpContext = true;
        public bool ExceptionOnNoHttpContext
            get { return m_ExceptionOnNoHttpContext; }
            set { m_ExceptionOnNoHttpContext = value; }
        // The meat of the Appender
        override protected void Append(LoggingEvent loggingEvent)
            // optional test for HttpContext, set in config file.
            // default is true
            if (ExceptionOnNoHttpContext == true)
                if (HttpContext.Current == null)
                      "JSConsoleAppender: No HttpContext to write javascript to.");
            // newlines mess up JavaScript...check for them in the pattern
            PatternLayout Layout = this.Layout as PatternLayout;
            if (Layout.ConversionPattern.Contains("%newline"))
                  "JSConsoleAppender: Pattern may not contain %newline.");
            // format the Log string
            String LogStr = this.RenderLoggingEvent(loggingEvent);
            // single quotes in the log message will mess up our JavaScript
            LogStr = LogStr.Replace("'", "\\'");
            // Check if console exists before writing to it
            String OutputScript = 
              String.Format("if (window.console) console.log('{0}');", LogStr);
            // This sends the script to the bottom of the page
            Page page = HttpContext.Current.CurrentHandler as Page;
                       m_IDCounter++.ToString(), OutputScript, true);
        // There is no default layout
        override protected bool RequiresLayout
            get { return true; }

From the ASP.NET test application, here's the web.config file. In the pattern for the JSConsoleAppender, I added the word SERVER: to differentiate the lines from client logging. Note there are two other Appenders in the log…just for fun!

<?xml version="1.0"?>
  <!--<span class="code-comment">BEGIN log4net configuration--></span>
  <configSections >
    <section name="log4net"

             type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
    <appender name="LogFileAppender"

      <param  name="File" value="C:\Log4Net.log"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern"  value="%d %-5p %c %m%n"/>
    <appender name="TraceAppender"

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date  %-5level [%property{NDC}] - %message%newline" />
    <appender name="JSConsoleAppender"

      <layout type="log4net.Layout.PatternLayout">
        <!--<span class="code-comment">Note JSConsoleAppender cannot have %newline--></span>
        <conversionPattern value="SERVER: %date %-5level %logger:  %message  SRC: %location" />
    <logger name="MyLogger">
      <level value="ALL" />
      <appender-ref ref="LogFileAppender"  />
      <appender-ref ref="TraceAppender"  />
      <appender-ref ref="JSConsoleAppender"  />
  <!--<span class="code-comment">END log4net configuration--></span>
    <compilation debug="true"


Here's the default.aspx file from the test program, I added a bit of JavaScript and jQuery:

<%@ Page Language="C#" AutoEventWireup="true" 

          CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

<html xmlns="">
<head id="Head1"  runat="server">
    <title>Log4Net Test</title>
    <script src="Scripts/jquery-1.7.js" type="text/javascript"></script>
    <script type="text/javascript">
        function DocReady()
            if (window.console) 
                console.log("CLIENT: Doc Ready!");
    <form id="form1"  runat="server">
    <h5>Log4Net Test</h5>
        <asp:Button ID="ButtonLog" runat="server" Text="Do Some Logging!" 

            onclick="ButtonLog_Click" />   

Here's the default.cs file from the test program with some logging strings:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
public partial class _Default : System.Web.UI.Page
    private static readonly ILog log = LogManager.GetLogger("MyLogger");
    protected void Page_Load(object sender, EventArgs e)
    protected void ButtonLog_Click(object sender, EventArgs e)
        log.Info("Soft kitty, warm kitty");
        log.Warn("Little ball of fur");
        log.Error("Happy kitty, sleepy kitty");
        log.Fatal("Purr, purr, purr.");

And finally, here are the three output logs:

From the JSConsoleAppender (IE Developer Tools), it includes a client log call with the server log calls:

From the TraceAppender, the Visual Studio Output window:

From the LogFileAppender (using Notepad):

You can download the solution/projects/code here.

I hope someone finds this useful.


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


About the Author

Steve Wellens
EndWell Software, Inc.
United States United States
I am an independent contractor/consultant working in the Twin Cities area in Minnesota. I work in .Net, Asp.Net, C#, C++, XML, SQL, Windows Forms, HTML, CSS, etc., etc., etc.

You may also be interested in...

Comments and Discussions

QuestionMy Vote Of 5 Pin
melnac29-Jan-12 22:05
membermelnac29-Jan-12 22:05 
QuestionDoes not work in MVC3 Pin
Win32nipuh29-Jan-12 2:41
memberWin32nipuh29-Jan-12 2:41 
AnswerRe: Does not work in MVC3 Pin
Steve Wellens29-Jan-12 3:41
memberSteve Wellens29-Jan-12 3:41 
GeneralRe: Does not work in MVC3 Pin
Win32nipuh29-Jan-12 6:33
memberWin32nipuh29-Jan-12 6:33 
GeneralRe: Does not work in MVC3 Pin
szilardd31-Jan-12 2:13
memberszilardd31-Jan-12 2:13 
GeneralMy vote of 5 Pin
Win32nipuh27-Jan-12 3:01
memberWin32nipuh27-Jan-12 3:01 

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 | Cookies | Terms of Use | Mobile
Web04 | 2.8.190306.1 | Last Updated 23 Jan 2012
Article Copyright 2012 by Steve Wellens
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid