Logging in a C# library

I use log4net in my own library but I would not do this if my library should be used by others (i.e. outside of my organization). In that case I would use an interface for logging, provide a default implementation based on log4net in separate assembly and use one way or another to allow the users of the library to inject their own implementation.

Having said this: I really like log4net and would not use anything else, but I think it is wrong to force others to have to use the logging framework of your choice.

Edit:

  • I would also not consider it good practice having the library log to a file by default. The users of your library should be able to decide where log messages end-up.
  • I would also provide a "no-operation" implementation that can be used if no logging at all is required. This probably should be default behavior an not require any additional assemblies or steps to implement.

The beauty of using log4net is that your library doesn't have to specify where something is logged. The destination (log appenders) of the log messages is determined by the configuration, which is specified by the application (typically in a config file).

So yes, use log4net following their recommended patterns (a unique "logger" per class) and inform your users that your library uses log4net. Any log messages that your library code generates will be routed according to the consumers configuration (file, database, console, trace, etc).

EDIT: Here is a good short primer on log4net that explains the basic concepts.


All the answers here seems outdated. I will make a new one:

My library asks for an optional Microsoft.Extensions.Logging.ILogger object to write log messsages. Without the ILogger object then it simply won't log anything.

The consumer application can create this ILogger object using NLog, Log4Net or SeriLog.. and my library can be used in ASP.NET core application with no log framework lock-in.

Example creating a Microsoft ILogger with NLog

private static readonly ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
    builder.AddNLog();
 });
private static readonly ILogger<Program> log = loggerFactory.CreateLogger<Program>();

Example creating a Microsoft ILogger with log4net

ILoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddLog4Net(); //load log4net.config by default
log = loggerFactory.CreateLogger("T");

Tags:

C#

Logging