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

x
?
Solved

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

Posted on 2014-12-11
2
Medium Priority
?
2,811 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
[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
2 Comments
 
LVL 34

Accepted Solution

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

Industry Leaders: 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!

Question has a verified solution.

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

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…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

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