Solved

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

Posted on 2014-12-11
2
2,226 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 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

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

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

Suggested Solutions

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

730 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