Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2014-12-07
8
Medium Priority
?
4,954 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:Michael Fowler
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 34

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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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 34

Accepted Solution

by:
it_saige earned 2000 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 34

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 34

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

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

636 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