4

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' ?
1
  • Gurpreet Kailey Could you please share your code how you implemented serilog in class library. I am trying to implement it but not sure how to approach Commented Feb 11, 2020 at 16:23

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I got the following error : Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[ConnectionManagerProvider]' while attempting to activate 'ConnectionManagerProvider'. I have used in the class like private readonly ILogger _logger; public ConnectionManagerProvider(ILogger<ConnectionManagerProvider> logger) { _logger = logger; }
Along with the solution provided by Chris Pratt, make sure the 'MyClass' class should be added in the dependency of the asp.net core.
Gurpreet Kailey Could you please share your code how you implemented serilog in class library. I am trying to implement it but not sure how to approach
@veenapanakanapalli, I can not share the code complete code here, I will try to demonstrate in example. For that you have to wait for one day, let me know if its ok for you.
But then how do I use MyClass in say a gRPC service? If I do new MyClass() it will be expecting a logger in the constructor... But if I pass a logger in the constructor it will now be using the gRPC service's instance of the logger which is not what I want... I'm new at C# but it's insane to me how much "magic" there is here and have been googling for ages just to do simple logging from a class library... please help someone..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.