Solved

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

Posted on 2014-12-11
2
1,854 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 32

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

708 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

13 Experts available now in Live!

Get 1:1 Help Now