?
Solved

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

Posted on 2014-12-11
2
Medium Priority
?
2,554 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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
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.
Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Suggested Courses
Course of the Month14 days, 9 hours left to enroll

771 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