Solved

How to write logs to multiple files using log4net and C#?

Posted on 2014-12-11
2
2,031 Views
Last Modified: 2014-12-11
Hello Experts,

I am trying to logs to multiple log files from the same C# application. The want to pass the file names from my application. But I am getting the following error message and logging is not working

log4net: Opening file for writing [C:\projects\Trouble\Trouble\bin\Debug\(null)_20141211.log] append [True]
log4net:ERROR [RollingFileAppender] ErrorCode: GenericFailure. Unable to acquire lock on file C:\projects\Trouble\Trouble\bin\Debug\(null)_20141211.log. The process cannot access the file 'C:\projects\Trouble\Trouble\bin\Debug\(null)_20141211.log' because it is being used by another process.
log4net: Created Appender [MessageFileApp]
log4net: Adding appender named [MessageFileApp] to logger [MessageLogger].
log4net: Hierarchy Threshold []
log4net:ERROR [RollingFileAppender] ErrorCode: GenericFailure. AppenderSkeleton: No layout set for the appender named [LogFileApp].


app.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>

    <appender type="log4net.Appender.RollingFileAppender"  name="LogFileApp">
      <file type="log4net.Util.PatternString" value="%property{DeafultLogName}" />
      <appendToFile value="true" />
      <DatePattern value="_yyyyMMdd'.log'"/>
      <staticLogFileName value="false" />
    </appender>

    <appender type="log4net.Appender.RollingFileAppender" name="QueueFileApp">
      <file type="log4net.Util.PatternString" value="%property{QueueLogName}" />
      <appendToFile value="true" />
      <staticLogFileName value="false" />
      <DatePattern value="_yyyyMMdd'.log'"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d  %-5p %m%n" />
      </layout>
    </appender>

    <appender type="log4net.Appender.RollingFileAppender" name="MessageFileApp">
      <file type="log4net.Util.PatternString" value="%property{MessageLogName}" />
      <appendToFile value="true" />
      <DatePattern value="_yyyyMMdd'.log'"/>
      <staticLogFileName value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d  %-5p %m%n" />
      </layout>
    </appender>

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


    <logger name = "QueueLogger" additivity="false">
      <level value="ALL" />
      <appender-ref ref="QueueFileApp" />
    </logger>

    <logger name = "MessageLogger" additivity="false">
      <level value="ALL" />
      <appender-ref ref="MessageFileApp" />
    </logger>

  </log4net>

  <appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
  </appSettings>

  <system.diagnostics>
    <trace autoflush="true">
      <listeners>
        <add
            name="textWriterTraceListener"
            type="System.Diagnostics.TextWriterTraceListener"
            initializeData="C:\\projects\\Trouble\\Trouble\\log4net.txt" />
      </listeners>
    </trace>
  </system.diagnostics>

</configuration>

Open in new window


C# Code:

        private static readonly ILog dLogger = LogManager.GetLogger("FileLogger");
        private static readonly ILog qLogger = LogManager.GetLogger("QueueLogger");
        private static readonly ILog mLogger = LogManager.GetLogger("MessageLogger");

        static void Main(string[] args)
        {

            log4net.GlobalContext.Properties["DeafultLogName"] = @"C:\projects\Trouble\Trouble\default";
             log4net.Config.XmlConfigurator.Configure();

            dLogger.Info("This is DEFAULTAPP message.");


            log4net.GlobalContext.Properties["QueueLogName"] = @"C:\projects\Trouble\Trouble\queue";
            log4net.Config.XmlConfigurator.Configure();

            qLogger.Info("This is QUEUEAPP message.");

            log4net.GlobalContext.Properties["MessageLogName"] = @"C:\projects\Trouble\Trouble\message";
            log4net.Config.XmlConfigurator.Configure();
            mLogger.Info("This is MESSAGEAPP message.");

            Console.ReadLine();
        }
    }

Open in new window



Thanks for your help.
0
Comment
Question by:HPFE455
2 Comments
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 40494788
Look in your AssemblyInfo.cs and remove the line:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Open in new window


What is happening is that the Configuration of log4net is occuring before you set your properties (hence the (null)_20141211.log).  Once you remove that line then I would recommend this for your main method:
using System;
using log4net;

namespace EE_Q28578961
{
	class Program
	{
		private static readonly ILog dLogger = LogManager.GetLogger("FileLogger");
		private static readonly ILog qLogger = LogManager.GetLogger("QueueLogger");
		private static readonly ILog mLogger = LogManager.GetLogger("MessageLogger");

		static void Main(string[] args)
		{
			log4net.GlobalContext.Properties["DeafultLogName"] = @"C:\projects\Trouble\Trouble\default";
			log4net.GlobalContext.Properties["QueueLogName"] = @"C:\projects\Trouble\Trouble\queue";
			log4net.GlobalContext.Properties["MessageLogName"] = @"C:\projects\Trouble\Trouble\message";
			log4net.Config.XmlConfigurator.Configure();

			dLogger.Info("This is DEFAULTAPP message.");

			qLogger.Info("This is QUEUEAPP message.");

			mLogger.Info("This is MESSAGEAPP message.");
			Console.ReadLine();
		}
	}
}

Open in new window


The reason for this edit is because, again, if you run the log4net configuration in the way you are currently trying to use it, then at least one of your appenders will generate a null log file.

-saige-
0
 

Author Comment

by:HPFE455
ID: 40495000
Now I understand why my code was failed to generate the logs.
Thanks Saige, for your solution.
0

Featured Post

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

813 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

14 Experts available now in Live!

Get 1:1 Help Now