Recently I started working on a project which basically has the following structure:
As you can see, now we only support logging on the presentation layer where we have try/catch blocks expecting to handle errors from the business layer. So far, so good. But, recently I started to realize that I will need to log some processing information as well. Not only exceptions. If possible, in the same file where Presentation App 1, for example, is storing its logs.
So, for that purpose, the way I imagine it is that my business layer has some kind of generic interface implemented by Serilog and log4net (and probably other providers) and use it to do its logging. That's because I don't really want to add a specific logging package in my business layer project. In other words, I want it to be independent. So, I tried to look at some best practices. I covered this article which explains Managing Cross Cutting Concerns but I couldn't really understand how it will fit my case.
How can I use the logger (in my business layer project) which was dependency injected in my startup application?
UPDATE: The way I dependency inject my logger into the worker service clients is as follows:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(loggingBuilder =>
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
loggingBuilder.AddSerilog(logger, dispose: true);
})
where loggingBuilder is of type Microsoft.Extensions.Logging.ILoggingBuilder and the actual logger that I use in the application and is dependecy injected through the constructor of the worker
public Worker(ILogger<Worker> logger, IBusinessLayerService businessLayerService)
{
_logger = logger;
_businessLayerService = businessLayerService;
}
is of type Microsoft.Extensions.Logging.ILogger
With
Microsoft.Extensions.Logging.ILogger
you'll keep things pretty standard without any dependencies to neither Serilog nor log4net in Data Layer and Business Layer.
You inject logger like this
ILogger<YourBusinessClass>
This article describes how to use Serilog with default logger:
https://vmsdurano.com/serilog-and-asp-net-core-split-log-data-using-filterexpression/
Microsoft.Extensions.Logging
should be available to your application through Microsoft.AspNetCore.App
which has a dependency to Microsoft.Extensions.Logging.Configuration
which has a dependency to Microsoft.Extensions.Logging
. Hence, no need for adding extra Nuget package for Microsoft.Extensions.Logging
.