3

I am trying to move a project to .net standard and it basically is a class library. I am using log4net for logging and I was using the method

public static ILog GetLogger(string name);

As this is a library referenced by multiple projects, defining repository should not happen as each project referencing this one, defines it's own repository for logging. How can I circumvent this issue when it comes to porting to .Net standard?

John Demetriou
  • 4,093
  • 6
  • 52
  • 88
  • 2
    You should probably *not* use `ILog`. Use the `Microsoft.Extensions.Logging.Abstractions` interfaces instead and configure them to use log4net as the actual logger. You *can't* force users of your library to use Log4Net. The logging abstractions have become a defacto standard too, which means NuGet packages support them already – Panagiotis Kanavos Apr 09 '19 at 07:34
  • 2
    [This answer](https://stackoverflow.com/a/51950113/134204) shows how easy it is to integrate log4net with the logging abstractions. You can then use DI to inject the proper logger to each class and avoid static logger instances – Panagiotis Kanavos Apr 09 '19 at 07:38

1 Answers1

11

The implementation of GetLogger is simple:

public static ILog GetLogger(string name)
{
    return GetLogger(Assembly.GetCallingAssembly(), name);
}

Assuming you want to use your class library's assembly, you can write your own helper method for that easily:

private static ILog GetLogger(string name) =>
    LogManager.GetLogger(typeof(SomeTypeInYourLibrary).Assembly, name);

It's basically hard-coding the assembly to be "the assembly containing the type you've specified" which is what you'd always get from calling GetLogger(string) from your library anyway.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194