Solved

log4net configuration question

Posted on 2014-09-07
3
217 Views
Last Modified: 2014-09-08
Hi everyone, I have a log4net.config file that looks like this
<log4net>
  <appender name="MyTraceAppender" type="log4net.Appender.TraceAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="DEBUG"/>
    <appender-ref ref="MyTraceAppender"/>
  </root>
</log4net>

Open in new window

I have C# application that looks like this
using System.Diagnostics;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Trace.WriteLine("test");
        }
    }
}

Open in new window

My C# application App.config looks like this
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net configSource="log4net.config" />
  <startup> 
      <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
<appSettings>
  <add key="log4net.Internal.Debug" value="false"/>
</appSettings>
  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="MyLogfile.log"/>
      </listeners>
    </trace>
  </system.diagnostics>  
</configuration>

Open in new window

When I compile and run my C# application a file named MyLogfile.log is created and it contains the word "test" in there. All working !!!

I would like to modify my configuration so that everything that gets output to the log file is also displayed in the console at the same time.

I see that log4net also has a log4net.Appender.ConsoleAppender but I don't think this is what I am after. I want all output routed to the TraceAppender to go to the log file AND to the console/screen.

Is this possible and if so, what should my configuration file look like?

Thank you

John
0
Comment
Question by:John Bolter
  • 2
3 Comments
 
LVL 21

Expert Comment

by:MogalManic
ID: 40309922
Adding a console listener is as simple as adding it to the app config.  The console trace listener can be added like this:
 <listeners>
        <add name="configConsoleListener"  
          type="System.Diagnostics.ConsoleTraceListener" />
        <add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="MyLogfile.log"/>
</listeners>

Open in new window


Your code is not using log4net.  The call to Trace.WriteLine("test"); is writing to the tracelistener only.  If you want your logging to go through log4Net you need to change your sample code as follows:
Create a logger instance - This creates a "context" where the logging is from
Call the logging through the logging instance instead of the Trace message

So now your program would look like this:
using System.Diagnostics;
using log4net;
namespace ConsoleApplication1
{
    class Program
    {
        private static ILog log = LogManager.GetLogger(typeof(Program));
        static void Main(string[] args)
        {
            log.Debug("test");
        }
    }
}

Open in new window


The advantage of using log4net for your logging becomes more apparent when you have a large program.  You can choose the log levels in the log4net configuration and even choose which modules output into logging.  For example, I have some debugging logging in a Web Service that spits out the XML document passed into the web service.  It is off by default, but to turn it on, all I need to do is add the following lines into my log4net.config:
<logger name="MyWebService.XmlTransferClass.XmlIn">
    <level value="DEBUG"/>
    <appender-ref ref="xmlAppender" />
  </logger>
  <logger name="MyWebService.XmlTransferClass.XmlOut">
    <level value="DEBUG"/>
    <appender-ref ref="xmlAppender" />
</logger>

Open in new window


The contexts MyWebService.XmlTransferClass.XmlIn and MyWebService.XmlTransferClass.XmlOut are coded in my web service logging by creating a logger with the correct context string:
   private static ILog xmlInLogger = LogManager.GetLogger("MyWebService.XmlTransferClass.XmlIn");
   private static ILog xmlOutLogger = LogManager.GetLogger("MyWebService.XmlTransferClass.XmlOut");

Open in new window

0
 
LVL 21

Accepted Solution

by:
MogalManic earned 500 total points
ID: 40309944
If you want to configure the double logging inside the log4net config, then the log4net.config file would look something like this:
<log4net>
  <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
    <param name="File" value="LogFile.log" />
    <param name="AppendToFile" value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
    </layout>
  </appender>

  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
    </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="LogFileAppender" />
    <appender-ref ref="ConsoleAppender" />
  </root>
</log4net>

Open in new window


Since each appender is configured separately, the format of the message can be configured by changing the 'ConversionPattern' element.    For more information on configuring the log4Net message, see the documentation at:http://logging.apache.org/log4net/release/manual/configuration.html
0
 

Author Closing Comment

by:John Bolter
ID: 40310255
Thank you !!!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now