Initializing log4net in a WCF service

Before it can be used for logging, log4net has to be initialized. The initialization should happen once on application (or more accurately app domain) startup……

Back to blog

Before it can be used for logging, log4net has to be initialized. The initialization should happen once on application (or more accurately app domain) startup.

The correct way to initialize log4net in a WCF application hosted in IIS is to to add an ‘application initializer’ class in the App_Code folder of your wcf web project. The class has to be public and it has to have a parameterless public method named ‘AppInitiailze’. The namespace/name of the class is not important. Example,

The asp.net runtime will call the method exactly once for every app domain it creates to host your wcf service.

You can only have one class with the AppInitialize() method – if you have more than one you will get an error at runtime.

This is the only way to initialize log4net under asp.net given that you might have multiple services per project, non-http activation, different instance management, etc. Some of the other options you might be tempted to try that dont work correctly are,

  1. Put the initializer call in the constructor of the class that implements the service contract – doesnt work because the log4net initializer is not thread safe so will except under load
  2. Put the initializer call in the static constructor of the class that implements the service contract – have to repeat the code across all services in your project. Also not threadsafe
  3. Put the initializer call in app_startup in global.asax – doesnt work for non http activation