Solved

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

Posted on 2014-12-07
8
3,870 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
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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Library to convert HTML to PDF. 8 55
Name space syntax error 12 39
Data is not showing from images 15 36
Web Form VB.Net  import CSV 4 17
In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

932 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

10 Experts available now in Live!

Get 1:1 Help Now