Monday, July 16, 2018

C# Logging: Where To Setup The Logger

Applications need logging. In C#, you will typically log various types of events like exceptions, debug, and informational. Your logs will contain valuable information which you'll use to tune your application and understand user behavior.

It's easiest to either pass an enum value to a single Log method or call a specific method to write different types of events. It's typical to write to different logs depending on the context. The problem is, where and how do we access the logging API from our methods?

Dependency Injection


Dependency Injection is one possible approach. If you go this route, you have to pass around a logger to all your classes as a dependency. You can use constructor injection and take the logger in as a constructor parameter. For a User class, you would pass it in along with the UserRepository as follows:


public class User
{
  private readonly IRepository<UserData> _userRepo;
  private readonly ILogger _logger;

  public User(IRepository<UserData> userRepo, ILogger logger)
  {
    _userRepo = userRepo;
    _logger = logger;
  }
}


The User class takes in the logger along with any other dependencies.

Via IoC Container

Even if you use an IoC container like Ninject or Unity, you have to add the logging interface to all the constructors and make a class member. With the IoC container approach, you can also ask the container for the implementation.

Container.Get<ILogger>()?.LogError(...);

Results and specific approach may vary according to the container, but this will at least allow you to fetch the logger whenever you need it without having to pass it around.

The .NET Core Way

In .NET Core 2.1, there are two ways to go about it as written by Luke Latham. Luke recommends using the LoggerMessage class over the LoggerExtensions for high-performance applications.

The Problem With DI

But let's suppose that you're not using core and you don't like the idea of adding the logger dependency EVERYWHERE! It isn't a dependency of the class that has anything to do with the business logic of the class. It's an implied dependency of all classes in the application. If you first design the class without the logging dependency, then you have to add it when you need to use logging.

IoC containers make this easier, but what if you have static methods from which you need to log (it happens)? In that case, you don't have constructor variables. You could pass the logger in the method params, but then you're passing around a logger. That's not a particularly elegant pattern! For one thing, you end up with more parameters. Another, you get into the habit of passing things around you may or may not need.

As Global

If it's a dependency everywhere, it's a global dependency. I don't like globals for many things. They are for configuration and that's really about it. It's beneficial to have a global logger too!

I also don't recommend statics for most things. Well, the logger could be a static global so long as it doesn't have mutable state. In other words, so long as you set the logging configuration once and leave it along throughout the entire application lifetime.

Log.LogError(...);

And in your implementation of the static method, you can get it from the container or some other global context.


public static void LogError(params object[] logParams)
{
  Container.Get<ILogger>()?.LogError(logParams);
}

This is actually a better practice since you only have to change your Log class if you change IoC containers and the interface doesn't match. It's better separation of concerns (SOC). The place to change the logging is in the Log class rather than everywhere else!

Concluding


Most of the methods discussed here are fine and dandy. I'm just not a huge of fan of having to pass things around in every class. I wouldn't extend this idea to something like a repository though, those are business logic specific dependencies that actually have meaning to the class at hand. A User class taking a UserRepository is meaningful. Every class taking an ILogger has no meaning and actually distracts from the purpose of the classes.

In sum, global is the place for the logger!

No comments:

Post a Comment