Solved

Log4Net - How to write logs to multiple files/Console using C# application

Posted on 2014-12-07
8
3,685 Views
Last Modified: 2014-12-15
Hello Experts,

I have different applications which use the same app.config to write logs to a file or a console window. My app.config file is as follows

<log4net>
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <File value="C:\File1.log" />
    <AppendToFile value="true" />
    <rollongStyle  value="Composite" />
    <maximumFileSize value="200MB" />
    <layout type="log4net.Layout.PatternLayout">
      <ConversionPattern value="%date %messge%newline"/>
    </layout>
  </appender>

  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
    <File value="C:\File2.log" />
    <AppendToFile value="true" />
    <rollongStyle  value="Date" />
    <maximumFileSize value="100MB" />
    <layout type="log4net.Layout.PatternLayout">
      <ConversionPattern value="%date %messge%newline"/>
    </layout>

    <filter type="log4net.Filter.LevelRangeFilter">
      <acceptOnMatch value="true" />
      <levelMin value="INFO" />
    </filter>
    <filter type="log4net.Filter.LevelRangeFilter">
      <acceptOnMatch value="true" />
      <levelMin value="FATAL" />
    </filter>
  </appender>

  <appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
    <mapping>
      <level value ="ERROR"/>
      <foreColor value ="Red"/>
    </mapping>

    <mapping>
      <level value ="WARN"/>
      <foreColor value ="Yellow"/>
    </mapping>
    <layout type="log4net.Layout.PatternLayout">
      <ConversionPattern value="%date %messge%newline"/>
    </layout>
  </appender>

  <root>
    <level value="ALL" />
    <appender-ref ref="LogFileAppender" />
    <appender-ref ref="RollingFile" />
    <appender-ref ref="ColoredConsoleAppender" />
  </root>
</log4net>

Open in new window



In My c# project, I am trying to use "LogFileAppender" to write the logs to a file. But the issue is, it also sending the logs to the Console Window.

Question:
How can I stop sending the logs to the console when I use LogFileAppender using the above app.config file

Thanks for your help
0
Comment
Question by:HPFE455
  • 4
  • 3
8 Comments
 
LVL 23

Expert Comment

by:Michael74
Comment Utility
How are you declaring the logger in code. Something like this uses the default logger settings

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

Open in new window


try

private static readonly log4net.ILog log = log4net.LogManager.GetLogger
   (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Open in new window

0
 

Author Comment

by:HPFE455
Comment Utility
Thanks Michael74,

My logger setting was as follows,

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

I tried you solution but it didn't work.
0
 
LVL 32

Expert Comment

by:it_saige
Comment Utility
You will probably need to do something like this:
<!-- Add the following to your config file and remove\comment out the root section -->
<logger name = "FileLogger">
  <level value="ALL" />
  <appender-ref ref="LogFileAppender" />
</logger>

<logger name = "ConsoleLogger">
  <level value="ALL" />
  <appender-ref ref="ColoredConsoleAppender" />
</logger>

Open in new window


Then you would instantiate each logger as such:
private static readonly ILog fileLogger = LogManager.GetLogger("FileLogger");
private static readonly ILog consoleLogger = LogManager.GetLogger("ConsoleLogger");

Open in new window


-saige-
0
 

Author Comment

by:HPFE455
Comment Utility
I found the solution by modifying the app.config as follows.


      
	<logger name = "FileLogger" additivity="false">
		<level value="ALL" />
		<appender-ref ref="LogFileAppender" />
	</logger>

	<root>
		<level value="ALL" />
		<appender-ref ref="RollingFile" />
		<appender-ref ref="ColoredConsoleAppender" />
	</root>

Open in new window

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
Comment Utility
Set the additivity parameter to false for each logger that you do not want to bubble up to the root section:

For example -

App.config -
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<configSections>
		<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
	</configSections>
	<log4net>
		<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
			<File value="File1.log" />
			<AppendToFile value="true" />
			<rollingStyle  value="Composite" />
			<maximumFileSize value="200MB" />
			<layout type="log4net.Layout.PatternLayout">
				<ConversionPattern value="%date %messge%newline"/>
			</layout>
		</appender>
		
		<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
			<File value="File2.log" />
			<AppendToFile value="true" />
			<rollingStyle value="Date" />
			<maximumFileSize value="100MB" />
			<layout type="log4net.Layout.PatternLayout">
				<ConversionPattern value="%date %messge%newline"/>
			</layout>

			<filter type="log4net.Filter.LevelRangeFilter">
				<acceptOnMatch value="true" />
				<levelMin value="INFO" />
			</filter>
			<filter type="log4net.Filter.LevelRangeFilter">
				<acceptOnMatch value="true" />
				<levelMin value="FATAL" />
			</filter>
		</appender>

		<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
			<mapping>
				<level value ="ERROR"/>
				<foreColor value ="Red"/>
			</mapping>

			<mapping>
				<level value ="WARN"/>
				<foreColor value ="Yellow"/>
			</mapping>
			<layout type="log4net.Layout.PatternLayout">
				<ConversionPattern value="%date %messge%newline"/>
			</layout>
		</appender>

		<root>
			<level value="ALL" />
			<appender-ref ref="LogFileAppender" />
			<appender-ref ref="RollingFileAppender" />
			<appender-ref ref="ColoredConsoleAppender" />
		</root>

		<logger name="FileLogger" additivity="false">
			<level value="ALL" />
			<appender-ref ref="LogFileAppender" />
		</logger>

		<logger name = "ConsoleLogger" additivity="false">
			<level value="ALL" />
			<appender-ref ref="ColoredConsoleAppender" />
		</logger>
	</log4net>
</configuration>

Open in new window


AssemblyInfo.cs -
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("EE_Q28576072")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EE_Q28576072")]
[assembly: AssemblyCopyright("Copyright ©  2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c52f7bba-fde6-415a-8c41-91b935cee5a5")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers 
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Open in new window


Program.cs -
using System;
using log4net;

namespace EE_Q28576072
{
	class Program
	{
		private static readonly ILog fileLogger = LogManager.GetLogger("FileLogger");
		private static readonly ILog consoleLogger = LogManager.GetLogger("ConsoleLogger");
		static void Main(string[] args)
		{
			fileLogger.Warn("This is a test warning message written to the file.");
			consoleLogger.Warn("This is a test warning message written to the console.");
			Console.ReadLine();
		}
	}
}

Open in new window


Produces the following console output -

And create a File in the application directory called File2.log -

With the following contents -Capture.JPG
0
 
LVL 32

Expert Comment

by:it_saige
Comment Utility
Ack.  You beat me to it.  ;)

-saige-
0
 

Author Comment

by:HPFE455
Comment Utility
Saige,

I would like to accept your detailed solution. But I couldn't find any option to change the accepted solution.

Thanks
0
 
LVL 32

Expert Comment

by:it_saige
Comment Utility
You can always request to reopen the question so that you can reassign the points or change the accepted solution.

At the top of the question you will see something like:Capture.JPGYou would choose the 'Request Attention' link in order to have the question reopened.  Just be sure to provide the reason for the requested attention.

Here is the link reposted: Request Attention

-saige-
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

763 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

7 Experts available now in Live!

Get 1:1 Help Now