15

I have a solution consisting of a main winforms app, with associated internally written class library dll’s from which I wish to log. This logging should performed by the same logger, regardless of whether the main UI client or the associated dll’s call this. The dll’s may of course be used by other apps that have different loggers in other solutions, but in these circumstances will have a different log4net config and maybe a different suite of appenders altogether.

One approach would be to create a singleton within the main app and log from that, however since log4net is its own singleton, that can be referenced so as long as we pass the same string (or type) to log4net.LogManager.GetLogger we will be logging to the same destination (in my case I wish to use a RollingFileAppender).

This works. However, given that the DLL will have a number of classes it would mean each class instantiation or static class from which we wish to log would require i) an argument defining the logger name (in order to log to the same destination) and ii) at each entry point would need to call log4net.LogManager.GetLogger(loggerName).

What is the best pattern to use here? Would the correct approach be to create a singleton instance in each assembly? My concern here is that we will still need to pass in the logger name to each entry point for the dll, which seems like overkill. In order to avoid passing in the logger name, I might assume that it is always equal to System.Reflection.Assembly.GetCallingAssembly().GetName().Name.

If this is all too difficult for log4net, are there other easier solutions such as the Enterprise Logging Block? Or is the best solution an aspect oriented programming (AOP) approach?

Reference for anti-pattern approach for singleton here .

Community
  • 1
  • 1
Topdown
  • 443
  • 1
  • 8
  • 17

6 Answers6

19

Almost one year later, but I thought I would contribute anyway!

Based on your comment to Carl's post, I think that maybe you misunderstand how log4net works. Yes, the loggername does identify the logger. Yes, a logger can have many appenders. BUT, many loggers can also write to the SAME appender. So, you could configure loggers "A", "B", and "C" to all log to file "X". You can get the loggers like this:

ILog logger_a = LogManager.GetLogger("A");
ILog logger_b = LogManager.GetLogger("B");
ILog logger_c = LogManager.GetLogger("C");

Now, if you log with any of these loggers, they CAN all go to the same place (file "X") if you configured them that way.

The advantage to NOT using the same logger name throughout your application is that you can control the level of logging in different places in your application via the config file. So, if the code that is using loggers "A" and "B" is working fine, but the code that is using logger "C" is having a problem, you could turn "A" and "B" off, and turn "C" all the way up. That way you have less information to have to dig through to find your problem.

Most people (or at least most log4net examples) actually create a static logger instance per CLASS, named for that class (I don't remember the exact syntax but it is easy to find examples). This gives you a very high level of granularity for controlling your logging.

In your app.config file, you can control all loggers at the same level by configuring a single logger called "*" or you can configure specific loggers (by using the fully qualified typename) or you can even configure by part of the fully qualified typename. For example, you could very easily make all classes in namespace ABC log at "info" level, all classes in namespace DEF log at "error" level, and all classes in namespace GHI not log at all. AND all of these loggers can log to the same destination (e.g file X).

Might have been too late to help, but maybe not...

wageoghe
  • 27,390
  • 13
  • 88
  • 116
  • In my original question I decided that much of what I wished to log was actually progress feedback and so I published events that the main app consumed, but your explanation here is by far the clearest, and I have used this elsewhere also. – Topdown Nov 03 '10 at 07:00
3

First, you should create a wrapper class (to decouple your app from the logging provider).

This wrapper class could take the logger identifier. If you're using an IoC container, you could just inject the name of the logger, or an existing, pre-configured, instance.

If you're using Unity (other containers are similar), you could do something like

// During application initialization
IUnityContainer myContainer = new UnityContainer();
LoggingService concreteLoggingService = new LoggingService( "logID" );
myContainer.RegisterInstance<ILoggingService>( concreteLoggingService );

// This would be injected, so you wouldn't see this, but it's here for consistency
ILoggingService loggingService = myContainer.Resolve<ILoggingService>();
loggingService.LogMessage( "message" );

Now, this assumes you have an IoC container. You can alternatively create a service locator:

// During application initialization
ServiceLocator.Register<ILoggingService>( new LoggingService( "logID" ) );

// Retrieved as needed
ILoggingService loggingServce = LoggingServiceLocator.Locate<ILoggingService>();
loggingService.LogMessage( "message" );

In the second case you need to write all the plumbing code. With an IoC container, you get that out-of-the-box.

Ryan Emerle
  • 15,461
  • 8
  • 52
  • 69
  • 1
    Why -1? I would absolutely not recommend this approach. To "decouple" the logging framework from the provider is to inject another layer of indirection without gaining anything of value. The log4net usage pattern is simple to code and its simple to replace. Wrapping it in anoter layer of indirection gives you no value and is a theoretical solution to a non-issue. – Casper Leon Nielsen Jan 02 '13 at 07:22
  • 1
    @Casper, I find the abstraction is useful to allow mocking during unit tests. – Barracoder Jan 07 '16 at 14:08
  • 1
    I understand the words you use, but what you describe is, in my view, misunderstanding the nature of your logger. Why would you needlessly abstract something that gives you extra production code, more production failure points and nothing of value - just to satisfy some cocked up requirement to "abstract everything in unit test". Log4Net in itself is already abstracted in such a way that it does not - nor ever will - influence your unit tests. – Casper Leon Nielsen Jan 08 '16 at 09:33
1

I have never seen another, meaningful, usage pattern than this for log4net:

On top of any class that needs logging, do:

private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

In the host layers AssemblyInfo.cs, do:

[assembly: log4net.Config.XmlConfigurator]

In the host startup either do programmatic setup of the appenders etc, or use plain app.config configuration.

End of story. No wrappers. No derivation from the above.

Each and every other usage pattern I have come across, is made to circumvent not really understanding log4net appenders, including some/all of the answers here.

Casper Leon Nielsen
  • 2,528
  • 1
  • 28
  • 37
  • If i have one single library (core) of logger, but referenced in different layers, this static initialization of logger always keeps logger as (core) library only but as referenced library. do you have any suggestion for this? – HydPhani Jan 10 '14 at 18:44
  • Seems like you do not want to go with the approach I recommend here, but instead want to wrap log4net. I do not recommend this, but if you are desperate to this anyways, check the answers here: http://stackoverflow.com/questions/166438/what-would-a-log4net-wrapper-class-look-like – Casper Leon Nielsen Jan 14 '14 at 10:59
1

I guess you could have the loggerName in your app.config.

May I ask why the loggerName has to be the same for the whole application?

Carl Bergquist
  • 3,894
  • 2
  • 25
  • 42
  • My understanding is that the loggername is the identifier of a logger. Where a logger can have many appenders. So if I want to use the same appenders and in the case of RollingFileAppender log to the very same file from dll's then I need to have the same loggername for each call to GetLogger. Or have I misunderstood? – Topdown Nov 11 '09 at 12:10
  • @Topdown: You have misunderstood. You should familiarize yourself with http://logging.apache.org/log4net/release/faq.html – Casper Leon Nielsen Jan 02 '13 at 07:34
0

We followed an approach for using log4net similar to this.

We use log4net in both the main app and class library assemblies. We wrote a wrapper class around it, so that all the logging appears with the same sort of configuration from everywhere we call it and also to make sure its a singleton. This wrapper class is called from everywhere within our app.

As a result, the class libraries and the main app all log out to the same log file with the same configuration, which is what we wanted. Is this what you were trying to achieve?

Paul Fedory
  • 307
  • 3
  • 9
0

How about implementing your own TraceListener so that you can just use Trace.Write throughout your application?

Philip Wallace
  • 7,905
  • 3
  • 28
  • 40
  • How is this connected to the question? – Casper Leon Nielsen Jan 02 '13 at 07:29
  • @CasperLeonNielsen You implement a custom TraceListener (which is part of .NET) that writes to the log using Log4net. Add it to the Listeners collection (part of .NET) on startup, then in whatever dll or class or whatever you want, use Trace.Write (part of .NET) and it ends up in your Log4net log file. – Philip Wallace Jan 04 '13 at 21:37
  • Let me rephrase that: That is not connected to the question. What you are proposing is a way to circumvent the normal usage scenario for log4net, gaining nothing at all other than increased complexity. – Casper Leon Nielsen Jan 07 '13 at 07:46