Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4Net in WCF not working

Tags:

wcf

log4net

Hi I am trying to use Log4Net in WCF IIS hosted service, but it doesn't log any data. Has anyone achieved logging in WCF service using Log4Net?

like image 567
RockWorld Avatar asked Jan 05 '11 08:01

RockWorld


People also ask

Where do I put log4net in web config?

Now, add the section "<log4net></log4net>" after the <configSections/> element in your app. config file. Next, inside the "<log4net></log4net>" section, place the configuration details as shown in the code snippet given below. That's all you need to do to configure log4net.

What is the use of log4net DLL?

The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. log4net is a port of the excellent Apache log4j™ framework to the Microsoft® . NET runtime.


2 Answers

I'm successfully using log4net on my project within a self-hosted WCF application.

Our steps to setup are fairly straightforward.

  1. Add reference to log4net.dll to our console service host project (our application entry point)
  2. Add the following line to the above project's AssemblyInfo.cs file (allows a custom log4net config file to be specified, which log4net will "watch" for updates. Quick, but maybe a bit dirty..)

    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

  3. Add log4net.config file to console project and copy it to the output directory (file properties: "Copy to Output Directory")

  4. Add log4net.dll reference to all projects where you require logging
  5. Declare the logger as private static member of the classes where you need logging:

     private static readonly log4net.ILog Logger = 
     log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
  6. Log where required:

    Logger.Info("Starting console service host");

This article pretty much covers it: http://haacked.com/archive/2005/03/07/ConfiguringLog4NetForWebApplications.aspx

like image 85
Pero P. Avatar answered Oct 12 '22 01:10

Pero P.


Another thing to be careful of is when you have a custom WCF ServiceHostFactory defined in a separate assembly to your Wcf endpoint (eg to keep DRY) then the assembly where the factory is defined is the the "root" assembly from the point of view of log4net and the XmlConfigurator attribute needs to be declared in that assembly.

This FAQ http://logging.apache.org/log4net/release/faq.html#trouble-webapp-stops-logging and linked comments explain that log4net wants to initialize as soon as possible

like image 20
Peter McEvoy Avatar answered Oct 12 '22 00:10

Peter McEvoy