Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5797
  • Last Modified:

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

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
HPFE455
Asked:
HPFE455
  • 4
  • 3
1 Solution
 
Michael FowlerSolutions ConsultantCommented:
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
 
HPFE455Author Commented:
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
 
it_saigeDeveloperCommented:
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
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
HPFE455Author Commented:
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
 
it_saigeDeveloperCommented:
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
 
it_saigeDeveloperCommented:
Ack.  You beat me to it.  ;)

-saige-
0
 
HPFE455Author Commented:
Saige,

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

Thanks
0
 
it_saigeDeveloperCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now