Solved

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

Posted on 2014-12-07
8
4,302 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 23

Expert Comment

by:Michael74
ID: 40486204
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
ID: 40486724
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 33

Expert Comment

by:it_saige
ID: 40486785
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:HPFE455
ID: 40487013
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
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 40487024
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 33

Expert Comment

by:it_saige
ID: 40487029
Ack.  You beat me to it.  ;)

-saige-
0
 

Author Comment

by:HPFE455
ID: 40487058
Saige,

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

Thanks
0
 
LVL 33

Expert Comment

by:it_saige
ID: 40492363
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

749 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