dontbesorry80
dontbesorry80

Reputation: 597

ASP.Net 5 Logging in Class Libraries

I am a little new to dependency injection. I'm trying to get started with ASP.NET 5 and am struggling to figure out how to use services in my ASP.NET 5 class libraries. Especially the simple things like logging and EF data access.

For example I have followed the guide here: http://docs.asp.net/en/latest/fundamentals/logging.html

This has enabled me to have logging in the main application. How do I then output log events in my class library?

I'm aware that it is bad practice to reference the main application from the class library and wanted to figure out how to do it correctly.

Upvotes: 5

Views: 4554

Answers (1)

agua from mars
agua from mars

Reputation: 17404

Create a logger for your class by passing an ILogger<YourClass> in the constructor exactly like in the sample:

public class MyClass : IMyClass
{
     private readonly ILogger<MyClass> _logger;

     public (ILogger<MyClass> logger)
     {
        _logger = logger;
      }

    public void MyMethod()
    {
        _logger.LogInformation("a log");
    }
}

Or pass an ILoggerFactory:

public class MyClass: IMyClass
{
     private readonly ILogger _logger;

     public (ILoggerFactory loggerFactory)
     {
        _logger = loggerFactory.CreatLogger("MyClass");
      }

    public void MyMethod()
    {
        _logger.LogInformation("a log");
    }
}

And resolve your class by Dependency Injection:

services.AddTransient<IMyClass, MyClass>();

Then you can use it in your controller:

[Route("api/[controller]")]
public class TodoController : Controller
{
    private readonly IMyClass _myClass;
    private readonly ILogger<TodoController> _logger;

    public TodoController(IMyClass myClass, 
        ILogger<TodoController> logger)
    {
        _myClass = myClass;
        _logger = logger;
    }
}

Upvotes: 5

Related Questions