Search code examples
asp.net-core-1.0serilog

Serilog : How to use logging in 'Class Library' of asp.net core


I am using Serilog for logging in asp.net core website and there is 'class library' used in the project.

  1. How can we implement logging in asp.net core class library?
  2. Is there any way to implement logging independently in 'class library' ?

Solution

  • Simply, you add the Microsoft.Extensions.Logging NuGet package to your class library, and then inject ILogger<T> into your classes:

    public class MyClass
    {
        private readonly ILogger _logger;
    
        public MyClass(ILogger<MyClass> logger)
        {
            _logger = logger;
        }
    
        public void DoSomething()
        {
            _logger.LogInformation("I'm doing something here.");
        }
    }
    

    ILogger is a facade, an API for logging that doesn't actually do any logging itself. The actual logging happens via providers that you plug into the facade when you have a real application using it. This is where something like Serilog would come in. In your actual application, you'd configure logging to use Serilog, and then any time anything calls a method on ILogger, that gets proxied over to your actual real logging provider (Serilog), and then Serilog does the actual logging.